views:

1346

answers:

3

Hi!

I am trying to create a webpage where users can insert a pin (like google map) in between the text using context menu.

My problem is that i do not know how to insert the pin at the exact position. Using the DOM I can arrive only to the nearest DIV (by using this) but a DIV contains a lot of text and the PIN has to be positioned next to the text.

I can obtain the position of the mouse click using pageX and pageY but dont know how to insert an element at that position. I tried in JQuery: insertAfter, prepend, append but not getting the desired result.

Any idea how to solve this problem.

regards, choesang tenzin

 $("#Content").rightClick( function(e) {

 $("<div class='pin'/>").insertAfter(this); 
 });
+2  A: 
$("#Content").rightClick( function(e) {
        var myTop = ...;
        var myRight= ...;
        $("<div class='pin' style='position:absolute; top: ' + myTop +'px; right: ' + myRight + 'px;/>").insertAfter(this); 
 });

sorry, i don't remember how to get x and y from the e parameter. Also, you will need to convert x,y of mouse click to x,y relative to #content element.

Alex Reitbort
There's a couple of options for x/y and it's a bit of a x-browser mess. It's likely jquery wraps it nicely, but the native options are lsited here (mouse events only): http://www.quirksmode.org/js/events_properties.html#position
annakata
thanks a lot it works!$("#Content").rightClick( function(e) { var x = e.pageX-5; var y = e.pageY - 18; $("<div class='pin' style='top: " + y + "px; left: " + x + "px';></div>").insertAfter(this); });
tchoesang
A: 

Set the style position:relaitve; on the containing div, so that it becomes a layer. That way it works as origin for the absolutely positioned elements inside it.

Guffa
A: 

Hi All!

Thanks alot for all your ideas. I have come up with another way to do it. I am using the "RANGE" to insert directly into the clicked zone (div) and not after or before it and adding z-indexes. The positive points with this is:

  1. It is really into the text and not as a layer
  2. texts flow around the pin (text makes space for the pin)

    $("div").click( function(e) { //the following works only for FF at the moment var range = window.getSelection().getRangeAt(0); var pin = document.createElement('img'); pin.setAttribute('src','pin_org.png');
    pin.setAttribute('class','pin'); range.insertNode(pin); });

    $("img.pin").live( 'mouseover', function () { alert("hovered!!"); } );

tchoesang