0

I have a little problem / question. I work on a little WYSIWYG editor. I use a div with the option contentEditable="true" and I would like to know when there is a click on a button which element in my div is modifying by the user.

For example if there is 3 paragraphs on the the div, and that user modifies the second, I would like to know when he clicks on a button that he is currently to modify the second paragraph to show the text content ! In this example "P2" :

<div contenteditable="true"><p>P1</p><p>P2</p><p>P3</p></div>

Thanks in advance for your help.

Nicolas

sanceray3
  • 185
  • 2
  • 11

1 Answers1

0

You could examine the selection in the mousedown event of the button. The following will work in all major browsers:

function getSelectionBoundaryContainerElement(start) {
    var container = null;
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0);
            range.collapse(start);
            container = range.startContainer;
            if (container.nodeType != 1) {
                container = container.parentNode;
            }
        }
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        textRange.collapse(start);
        container = textRange.parentElement();
    }
    return container;
}

document.getElementById("yourButtonId").onmousedown = function() {
    alert(getSelectionBoundaryContainerElement().innerHTML);
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536