javascript - jQuery how to align a div using event coordinates? -


i have map earth , want set marker user clicking (like on google maps).

<div class='map_wrapper'> <div class='marker'></div>     <img src="images/map.jpg" alt="" usemap="#world_map" />      <map name="map_coords" id='world_map'> <area shape="poly" class='europe' name="europe" coords="468,186,468,191,463,194,460,199,458,205" />      </map> </div>  <style type='text/css'> .map_wrapper { position:relative; } .marker {    position:absolute;    width:25px;    height:34px;    background:url(../images/marker.png) top center no-repeat;    z-index:2; } </style> 

and javascript

$(document).ready(function(){     $('.map_wrapper area').click(function(ev){         var offset = $(this).offset();         var mobj = $('.marker');          mobj.css({             'margin-left' : (ev.clientx - offset.left - (mobj.width()/2) ) + 'px',             'margin-top' : (ev.clienty - offset.top) + 'px'         });     }); }); 

applying margin-left marker working, i'm having problem y (vertical) alignment. don't know how calculate px margin-top.

you can mouse position user clicks event.pagex , event.pagey. figures give absolute position top left of document. if move marker top of document can use values. otherwise you'll need take off top , left of relative container.

$(document).ready(function(){     $('.map_wrapper area').click(function(ev){         var mobj = $('.marker');          mobj.css({             'left' : ev.pagex + 'px',             'top' : ev.pagey + 'px'         });     }); }); 

at moment work if click inside europe. if want able click anywhere attach event image , can rid of map.

http://docs.jquery.com/tutorials:mouse_position


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -