Ven ek Ven ek - 2 months ago 20
Javascript Question

Div is not moving + player movement

My function is not working, my div is not moving, whats wrong?

function moveAnimate(x, y, element) {
var leftX = document.getElementById(element).style.left;
var topY = document.getElementById(element).style.top;

leftX += x;
topY += y;

$(element).animate({
"top": topY,
"left": leftX,
}, 1000);
};

$(document).ready(function() {
$("#divv").on("click", function() {
moveAnimate(400, 400, this);
});
});


Here is normal div:

<div id="divv"></div>


And normal css:

#divv {
position: absolute;
height: 100px;
width: 100px;
background-color: blue;
left: 100px;
top: 100px; }


I don't know what's wrong with this code, why its not working?

And I have no idea how to do script to player movement, any ideas? I just want to set a player in the middle of some div and when I click somewhere player will go there. Can someone do that little script in easiest way and explain it to me?

Answer

You pass the element to the function so you need to use $(element) and get the position of the element:

function moveAnimate(x, y, element) {
   var elementPosition = $(element).position();
   var leftX = elementPosition.left;
   var topY = elementPosition.top;

   leftX += x;
   topY += y;

$(element).animate({ 
    "top": topY, 
    "left": leftX,
}, 1000);    
}; 

$(document).ready(function() {
    $("#divv").on("click", function() {
        moveAnimate(400, 400, this);
    });
});
#divv {
        position: absolute;
        height: 100px;
        width: 100px;
        background-color: blue;
        left: 100px;
        top: 100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divv"></div>