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 ?
I suggest using a simple flag to prevent the infinite loop. The
window.setTimeout()
call is there because theselectionchange
event doesn't fire synchronously whendocument.execCommand()
is called.Demo: http://jsfiddle.net/rzmstcot/5/
Code: