Friday, January 23, 2015

Add div element on click in a certain coordinate using jquery

Add div element on click in a certain coordinate using jquery
Using jquery offset, we will get the coordinates of the clicked area then add an box on that spot.
$('#layoutSpace').click(function(e){    
    var offset = $(this).offset();  
    areaBox = 50;//to center the mouse point
    mouseX = (e.pageX - offset.left - areaBox );
    mouseY =  (e.pageY - offset.top - areaBox );   
    $('#layoutSpace').append('
'); });
to center the box coordinate we will divide our box into 2
in my case, my box width and height is 100px so i will divide it to 2 and that would be 50.
areaBox = 50;//to center the mouse point
after that we will minus it to our x and y axis to center it up
  mouseX = (e.pageX - offset.left - areaBox );
  mouseY =  (e.pageY - offset.top - areaBox );
Live Demo

No comments:

Post a Comment