Does anyone know how to create an HTML element and then drag it across the screen?
I have a function that defines the movement of the element, and I can click on the header to drag the div wherever I want. Additionally, I created a button to add a new div item. Even though the new div appears correctly with the applied styles, there is an issue when trying to use both functions together.
The console error 'Cannot set property 'onmousedown' of null at dragElement' keeps appearing regardless of whether the div item is created before or after running the function.
I've attempted invoking the newHTMLitem() function within dragElement(), but it doesn't solve the problem. On the contrary, if newHTMLitem() is invoked at the end of the script, the HTML item does not show up at all. Any suggestions on how to resolve this issue?
document.getElementById('addItem').addEventListener('click',function newHTMLitem(){
let div = document.createElement('div');
div.classList.add('mydiv');
let header = document.createElement('div');
header.classList.add('mydivheader');
let body = document.createElement('p');
div.appendChild(header);
div.appendChild(body);
document.body.appendChild(div);
}
);
//Make the DIV element draggagle:
dragElement(document.querySelector(".mydiv"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.querySelector(".mydivheader")) {
/* if present, the header is where you move the DIV from:*/
document.querySelector(".mydivheader").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;
}
}