How to insert an element in DIV at position X Y

Clash Royale CLAN TAG#URR8PPPHow to insert an element in DIV at position X Y
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);
});
3 Answers
3
$("#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.
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): quirksmode.org/js/events_properties.html#position
– annakata
Mar 5 '09 at 16:46
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); });
– Choesang
Mar 5 '09 at 16:52
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.
position:relaitve;
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:
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!!");
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Shouldn't $("<div class='pin'/>").insertAfter(this); be $("div.pin").insertAfter(this); ?
– Ryan Graham
Mar 5 '09 at 14:32