jQuery HTML Element How to - Move div element after clicking








Question

We would like to know how to move div element after clicking.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.4.2.js'></script>
<style type='text/css'>
#example1 {<!--from  www  . j ava2 s .c om-->
  position: absolute;
  left: 100px;
  color:red;
}

#ship {
  position: absolute;
  color:red;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
$(document).ready(function() {
    $('#example1').click(function(e){
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        $('#example1-xy').html("X: " + x + " Y: " + y);
        var leftOfShip = x;                                              
        $("#ship").animate({left : leftOfShip},5000);;
    });
  });
});
</script>
</head>
<body>
  <div>
    <a href="#" id="example1">CLICK</a>
  </div>
  <div id="example1-xy">X Y</div>
  <div id="ship">abc</div>
</body>
</html>

The code above is rendered as follows: