Moving a DIV using XUI
-
14-03-2021 - |
Question
I'm trying to create a dragging effect on a div using xuijs. I don't really know which event to look listen too and what to do with it to make it slide.
I need it to follow the cursor of the mouse (Only move on the x-axis)
Heres an example of what im typically trying to do
<div id="parent" style="width: 100px; height: 20px;">
<div id="slideMe" style="width: 50px; height: 20px;">
</div>
</div>
If slideMe is clicked and dragged, it should move from one end to another (the html above is just an example, it is of course not entirely correct)
Anyone have a general idea how this can be achieved?
Solution
You can add Even Listener to mouse to capture mousemove.
window.addEventListener('mousemove', mouseMove, false);
Then you can move your div with mouseMove
function. You can make that div fallow your cursor.
function mouseMove(e) {
if (IE) {
Xcord = event.clientX + document.body.scrollLeft;
Ycord = event.clientY + document.body.scrollTop;
} else {
Xcord = e.pageX;
Ycord = e.pageY;
}
if (Xcord < 0) Xcord = 0;
if (Ycord < 0) Ycord = 0;
document.getElementById('slideMe').style.top = Ycord + 'px';
document.getElementById('slideMe').style.left = Xcord + 'px';
return true
}
But before that you need to set your divs style like below
#slideMe{
position:absolute;
}
Edit: These functions make div to fallow your cursor. But you wanted to move it in another div to levf and right; Then you need to change these codes like below.
Style:
#slideMe{
position:relative;
}
Function:
function mouseMove(e) {
if (IE) {
Xcord = event.clientX + document.body.scrollLeft;
Ycord = event.clientY + document.body.scrollTop;
} else {
Xcord = e.pageX;
Ycord = e.pageY;
}
if (Xcord < 0) Xcord = 0;
if (Ycord < 0) Ycord = 0;
//document.getElementById('slideMe').style.top = Ycord + 'px';
document.getElementById('slideMe').style.left = Xcord + 'px';
return true
}