HTML change depending on where I click javascript / jQuery

On the html page, you may have code with two paragraphs, for example:

<hr /> <p>The first paragraph</p> <p>The second paragraph</p> <hr /> 

and very simple, these two tags will look like this:


First paragraph

Second paragraph


I am interested in letting the user click somewhere in the displayed HTML to insert a new element using jQuery. For example, if I click between the letter I and the letter r (just click, without highlighting / selection) in the word f * ir * st found in the first paragraph, I could insert a custom span element or whatever as in this place in the HTML code, which leads to something like this:

 <hr /> <p>The fi<span id="myCustomSpan"></span>rst paragraph</p> <p>The second paragraph</p> <hr /> 

Any ideas that might help me? My request excludes absolute positioning. This will not solve my problems.

+7
source share
3 answers

It's dirty, but uses contenteditable : http://jsfiddle.net/Jj9Mp/ .

 $('div').click(function(e) { $('div').attr('contenteditable', true); document.execCommand("InsertHTML", false, "<span class=red>!</span>") e.stopPropagation(); }); $(':not(div)').click(function(e) { if($(this).parents('div').length === 0) { $('div').attr('contenteditable', false); } else { $('div').click(); } e.stopPropagation(); }); 
+2
source

Here is my solution: http://jsfiddle.net/gion_13/L6aeT/
It works by calculating the actual size (in px) of the string.

+2
source

This can be done with a few complex scripts.

I can specify an algorithm that you can try.

1.JQuery has an offset API () http://api.jquery.com/offset/ , using this, you can get the offset and element.

2. Now you need to take the innerHTML of the element, take it as a string from the offset Y val, split at the position Y in the string. make an element as two elements.

3. Now you can directly create an element in the script using creteElement (tag) and set innerHTML and then insert it between two elements

+1
source

All Articles