JavaScript selectionchange-EventListener, triggering infinitely on document.execCommand

2.3k views Asked by At

I have added an event listener for selectionchange as below,

document.addEventListener("selectionchange", 
function()
{
    highlight();
    console.log("selectionchange-triggered");
}, false);

then I have added the below code, to highlight selected text.

function highlight()
{
    document.designMode = "on";
    document.execCommand("hiliteColor", false, "#ff0000");
    document.designMode = "off";
}

When the highlight function is called, the EventListener for selectionchange is fired infinitely until I clear the selection.

have any one faced the same issue ? can any one suggest a solution to solve this issue ?

1

There are 1 answers

4
Tim Down On

I suggest using a simple flag to prevent the infinite loop. The window.setTimeout() call is there because the selectionchange event doesn't fire synchronously when document.execCommand() is called.

Demo: http://jsfiddle.net/rzmstcot/5/

Code:

var highlighting = false;

function highlight()
{
    document.designMode = "on";
    highlighting = true;
    document.execCommand("hiliteColor", false, "#ff0000");
    document.designMode = "off";
    window.setTimeout(function() {
        highlighting = false;
    }, 1);
}

document.addEventListener("selectionchange", 
function()
{
    if (!highlighting) {
        highlight();
    }
    console.log("selectionchange-triggered");
}, false);