i have a div that contains some text and i want to be able to move that div when i click and hold my left mouse button and when my pointer cursor location is changed the div location is changes too. my js code:
$(() => {
$(document).on("mousemove", "#div", (e) => {
const x = e.pageX
const y = e.pageY
$("#div").css("top", y - 50)
$("#div").css("left", x - 100)
console.log(e.pageY)
console.log(e.pageX)
})
})
my html code:
<div id="div">
<span>Hello World!</span>
<span>Look at Me!</span>
<span>I'm Moving!</span>
</div>
my problem is that i don't know to use which event. i want click and mousemove events together. what should i do now?
Consider the following example, based on the following Demo.
$(function() {
$("#draggable").draggable({
drag: function(event, ui) {
console.log(event.pageX, event.pageY);
}
});
});
#draggable {
width: 150px;
height: 150px;
padding: 0.5em;
}
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<div id="draggable" class="ui-widget-content">
<span>Hello World!</span>
<span>Look at Me!</span>
<span>I'm Moving!</span>
</div>