Why doesn't window.getSelection() on focus work in Chrome in this example?

I'm trying to use window.getSelection() to return the node when a contenteditable div 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 JSFiddle here: http://jsfiddle.net/yftf24g6/

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

Can anyone explain why?

Answers:

Answer

In chrome(as I see) The focus event is fired as soon as you click on the editable element before you complete your selection. Adding the setTimeout solves the issue, but is an unreliable hack.

I would suggest you use mouseup event,

The mouseup event is sent 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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.