surendher surendher - 2 months ago 8
AngularJS Question

How to move a "div" to certain coordinates using Javascript?

I would like to know , how to position a div block dynamically to the place where mouse clicks.

I know how to get the value of coordinates of click dynamically.

I want to know how we can move the div block to that coordinate.

I tried the following codes in SO, but nothing is working

document.getElementById('someID').style.position='absolute';
document.getElementById('someID').style.left='500px';
document.getElementById('someID').style.top='90px';


and the below code

var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos;
d.style.top = y_pos;


Can anyone tell me how to do it.
Thanks,

Answer

You have missed the units in your position assigning sentence.

To get the mouse position (on click):

(function() {
    window.onmousedown = handleMouseMove;
    function handleMouseMove(event) {
        event = event || window.event; // IE-ism
        console.log(event.clientX);
        moveDiv(event.clientX,event.clientY);
    }
})();

Then send the position to a function to change the position of your div, adding the pixels unit, don't forget it!

function moveDiv(x_pos,y_pos){
    var d = document.getElementById('myDiv');
    d.style.left = x_pos + "px";
    d.style.top = y_pos + "px";
}

Full Code:

(function() {
    window.onmousedown = handleMouseMove;
    function handleMouseMove(event) {
        event = event || window.event; // IE-ism
        console.log(event.clientX);
        moveDiv(event.clientX,event.clientY);
    }
})();

function moveDiv(x_pos,y_pos){
    var d = document.getElementById('myDiv');
    d.style.left = x_pos + "px";
    d.style.top = y_pos + "px";
}

DEMO