Insert html element above the element closest to the mouse
I use drag and drop so users can move items around. When the element is dropped, I need it to be positioned correctly if the mouse is in the DOM tree. This is what I came up with:
var childnodes= e.target.children;
var mouse_x= e.clientX- e.target.offsetTop;
if(childnodes.lenght=== 0) e.target.appendChild(element);
else
{
for(var i = 0; i < childnodes.length; i++)
{
if(childnodes[i].offsetTop > mouse_x)
{
e.target.insertBefore(element, childnodes[i]);
break;
}
else if(i=== childnodes.length -1) e.target.appendChild(element);
}
}
But for some reason, client X is reconfiguring the wrong values.
No JS library please.
+3
source to share
1 answer
Not sure if that was where your problem was. Perhaps Rasel commented that the length was spelled incorrectly was the actual reason?
If it helps, there is a script here which I think is what you are looking for: https://jsfiddle.net/ruairitobrien/v1bcabnk/
Your code seems to work fine there. I've added it to a function that inserts the newly created element for illustration purposes.
function insertRandomThing(e) {
var element = document.createElement("div")
element.innerHTML = 'X: ' + e.pageX + ' Y: ' + e.pageY;
var childnodes = e.target.children;
var mouse_x = e.clientX - e.target.offsetTop;
if (childnodes.length === 0) {
e.target.appendChild(element);
} else {
for (var i = 0; i < childnodes.length; i++) {
if (childnodes[i].offsetTop > mouse_x) {
e.target.insertBefore(element, childnodes[i]);
break;
} else if (i === childnodes.length - 1) {
e.target.appendChild(element);
}
}
}
}
0
source to share