Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing HTML depending on where I click with javascript/JQuery

In an html page you might have some code with two paragraphs like this:

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

and very simply, these two tags would render like this:


The first paragraph

The second paragraph


What I am interested in is to allow the user to click somewhere in the rendered html code so as to insert a new element with JQuery. For example if I click between the letter i and the letter r (just a click, no higlighting/selection)in the word f*ir*st found in the first paragraph, I would be able to insert a custom span element or whatever I like exactly in that position in the HTML code resulting in something like this:

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

Any ideas that can help me? My request excludes absolute positioning. That would not solve my issues.

like image 368
prince Avatar asked Aug 30 '11 12:08

prince


3 Answers

This is dirty but makes use of 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();
});
like image 104
pimvdb Avatar answered Nov 04 '22 18:11

pimvdb


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

like image 20
gion_13 Avatar answered Nov 04 '22 17:11

gion_13


This can be done with somewhat complex scripting.

i can state an algorithm that you can try.

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

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

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

like image 1
Kris Avatar answered Nov 04 '22 19:11

Kris