StepUp
StepUp

Reputation: 38094

Cannot move "div" on handling "onclick" event

I would like to click on a div and that div would be moved and the div should follow my mouse.

What I have:

<div onclick="myFunction()" id="move"></div>


<script>
    function myFunction(){
        var div = document.getElementById('move');
        document.addEventListener('mousemove', function (e){
        div.style.left=e.pageX+"px";
        div.style.top=e.pageY+"px";
    });}
</script>

Upvotes: 2

Views: 124

Answers (2)

Manwal
Manwal

Reputation: 23816

Add this css:

div{
    position:absolute;
}

DEMO

Upvotes: 3

Pranay Rana
Pranay Rana

Reputation: 176896

Another thing you need is you need to set "Position:absolute" for the style of div.

Upvotes: 4

Related Questions