0

I'm trying to find a position in a string to append an <img> tag to on drop using jQuery.

What I'm planning on doing is on hover convert the HTML of a paragraph to string, or maybe a text area.

Is there a way to append HTML to the cursor's position?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Anthem127
  • 169
  • 2
  • 10

2 Answers2

1

If the X and Y coordinates are given, you can get the element by using document.elementFromPoint(x, y). Otherwise, you can get the X and Y by using the method as described in this answer.

So, let X and Y be given. Then:

function appendElementAt(img, x, y){
    var elem = document.elementFromPoint(x, y);
    var pos = elem.getBoundingClientRect();   //Calculate position of element
    var topPos = y - pos.top;                 // Calculate top position
    var leftPos = x - pos.left                // Calculate left positon

    elem.style.position = "relative";
    img.style.position = "absolute";
    img.style.top = topPos;
    img.style.left = leftPos;
    elem.appendChild(img);
}
// Usage:

var img = document.createElement("img");
appendElementAt(img, x, y);
Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • If you were looking to get the exact position of a certain text in an input field, I have previously spent hours on creating that, see: [this answer](http://stackoverflow.com/questions/6930578/get-cursor-or-text-position-in-pixels-for-input-element#7948715) – Rob W Nov 12 '11 at 21:35
  • Great guys, I can't wait to try these later :) – Anthem127 Nov 12 '11 at 21:49
1

Use window.getSelection() and Range :

http://www.quirksmode.org/dom/range_intro.html

http://help.dottoro.com/ljvhnwsk.php

fflorent
  • 1,596
  • 9
  • 11