Why is the window.getSelection () function not working in Chrome in this example?

I'm trying to use window.getSelection () to return a node when the contenteditable div object has been focused.

HTML:

<div id="testing" contenteditable="true">
   <p>Click on me while monitoring the console</p>
</div>

      

JQuery

$('#testing').focus(function() {
    console.log(window.getSelection());
});

      

See the JSFiddle here: http://jsfiddle.net/yftf24g6/

Watching the console, I am getting a text node selection in Firefox but not Chrome (Selection {type: "None"})

Can someone explain why?

+3


source to share


1 answer


In chrome (as I see it) the Event is focus

fired as soon as you click on the editable element, before finalizing your selection. The addition setTimeout

solves the problem, but is an unreliable hack.

I suggest you use an event mouseup

,

The mouseup event is dispatched to an element when the mouse pointer is over the element and the mouse button is released. Any HTML element can receive this event.



$('#testing').mouseup(function() {
    console.log(window.getSelection().toString());
});

      

Tested in Firefox (37.0.2) and Chrome (42.0.2311).

Updated Fiddle

+1


source







All Articles