How to create an auto increment id

In my project, While clicking a button, a div with contentEditable=true will be created on the screen. It should be happened again and again, whenever I am clicking on the button, new div should be created. All those created div should be draggable. For that purpose I am using following function.

function dragElement(elmnt) 
		    {
                var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
                if (document.getElementById(elmnt.id + "header")) 
                {
                    /* if present, the header is where you move the DIV from:*/
                    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
                }
                else 
                {
                    /* otherwise, move the DIV from anywhere inside the DIV:*/
                    elmnt.onmousedown = dragMouseDown;
                }
                
                function dragMouseDown(e) 
                {
                    e = e || window.event;
                    e.preventDefault();
                    // get the mouse cursor position at startup:
                    pos3 = e.clientX;
                    pos4 = e.clientY;
                    document.onmouseup = closeDragElement;
                    // call a function whenever the cursor moves:
                    document.onmousemove = elementDrag;
                }
                function elementDrag(e) 
                {
                    e = e || window.event;
                    e.preventDefault();
                    // calculate the new cursor position:
                    pos1 = pos3 - e.clientX;
                    pos2 = pos4 - e.clientY;
                    pos3 = e.clientX;
                    pos4 = e.clientY;
                    // set the element's new position:
                    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
                    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
                }
                function closeDragElement() 
                {
                    /* stop moving when mouse button is released:*/
                    document.onmouseup = null;
                    document.onmousemove = null;
                }
            }

But the problem is, for this function , the ID is needed to drag the object. Here I am creating the div again and again with the same ID. it cause the dragging . So I think I need to create the individual ID. But if I create like that, then how to get the id for dragging function. Please help me.

how are you creating the div can you show the code?

1 Like
var marker_tab=document.getElementById('markup');
		        var main_div = document.createElement('div');
		        main_div.setAttribute("id","mydiv");
		        var inner_div=document.createElement('div');
		        inner_div.setAttribute('id','mydivheader');
		        inner_div.innerText="\u2756	"
		        var editable_element=document.createElement('p');
		        editable_element.setAttribute('id','txt');
		        editable_element.setAttribute('contentEditable','true');
		        main_div.appendChild(inner_div);
		        main_div.appendChild(editable_element);
		        marker_tab.appendChild(main_div);
		        dragElement(document.getElementById("mydiv"));

you could do something like this. make elements with a class instead of id this way you can loop through the class and use the this function to grab the div, just an idea, a little sample so you get an idea of what i mean.

let main_div = document.createElement('div');
		        main_div.className = 'myDiv'
		        var inner_div=document.createElement('div');
		        inner_div.className = 'mydivheader';



let mydivheader = document.getElementsByClassName("mydivheader");

for (let i = 0; i < mydivheader.length; i++) {
  mydivheader[i].onclick = function() {
    let div = this.parentElement;
    div.onmousedown = dragMouseDown;
   }
  }
}
1 Like

Okay @biscuitmanz. Thank you for your reply

1 Like

This is also not working @biscuitmanz. :sleepy:

Hi!

When You create the div, have a function (a class, actually) like this:

function DivCreator() {
  let count = 0;

  this.createDiv = function() {
    count++;
    var marker_tab = document.getElementById('markup');
    var main_div = document.createElement('div');
    main_div.setAttribute("id", "mydiv-" + count);
    var inner_div = document.createElement('div');
    inner_div.setAttribute('id', 'mydivheader');
    inner_div.innerText = "\u2756	"
    var editable_element = document.createElement('p');
    editable_element.setAttribute('id', 'txt');
    editable_element.setAttribute('contentEditable', 'true');
    main_div.appendChild(inner_div);
    main_div.appendChild(editable_element);
    marker_tab.appendChild(main_div);
    dragElement(document.getElementById("mydiv"));
  };
}

const divCreator = new DivCreator();

// Then, on your button click that creates the div:

document.querySelector('.div-creator').addEventListener('click', () => divCreator.createDiv());

Look a this sample on jsfiddle.

Thank you @skaparate . But I need to drag this element. At that place only I am facing error. So can you please send the example with that also.

Something like this:

<div id="markup"></div>
<button class="div-creator">
  Create
</button>
.draggable {
  width: 30px;
  min-height: 30px;
  border: 1px solid black;
  position: absolute;
}

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

function DivCreator() {
  let count = 0;

  this.createDiv = function() {
    count++;
    const mainId = 'mydiv-' + count;
    var marker_tab = document.getElementById('markup');
    var main_div = document.createElement('div');
    main_div.classList.add('draggable');
    main_div.setAttribute("id", mainId);
    var inner_div = document.createElement('div');
    inner_div.setAttribute('id', 'mydiv' + count + 'header');
    inner_div.innerText = "\u2756	"
    var editable_element = document.createElement('p');
    editable_element.setAttribute('id', 'txt-' + count);
    editable_element.setAttribute('contentEditable', 'true');
    main_div.appendChild(inner_div);
    main_div.appendChild(editable_element);
    marker_tab.appendChild(main_div);
    dragElement(document.getElementById(mainId));
  };
}

const divCreator = new DivCreator();

// Then, on your button click that creates the div:

document.querySelector('.div-creator').addEventListener('click', () => divCreator.createDiv());
1 Like

Wow. Nice @skaparate. Thank you. But now the content editable is not working. Can you please do something for that?

Depending on what the rest of your code looks like, you could use a sequence number that you increment each time to create a unique ID. You may have to use a closure. In React you would use a state variable.

Another alternative could be to use the current time as the ID, for example, elmnt.id = Date.now(). This will work as long as enough time elapses between the creation of each element.

If this is part of a larger project, you may want to use the npm package uuid.

2 Likes

What I gave You was a sample, not a working project (well, it does something that You want, but not everything). The idea is that You mix the code I gave You and integrate it into Your project, otherwise I would be developing Your project :stuck_out_tongue:.

I don’t mean to be rude, I want You to learn :slight_smile:. Try to fix it, research and learn, then come back if the You still don’t understand.

2 Likes

Sure @skaparate . Thanks

Cool! Happy coding then :slight_smile:!

1 Like