1

I am trying to remove selection inside a contenteditable field. The code I have is this:

<h1 contenteditable>Text</h1>
<input type="text" value="Text" /><br/>
<input type="button" onclick="" value='Deselect input'>
<input type="button" onclick="$('h1').blur()" value='Deselect h1'>

And I'm auto-selecting the h1's text via document.execCommand('selectAll', false, null);

Removing the selection for the input works, but it does not work for the h1. How can I achieve this?

Check this fiddle


this photo shows how it behaves for me:

enter image description here

As you can see I just clicked deselect h1 and the text is still selected. I'm using Chrome.

Community
  • 1
  • 1
iuliu.net
  • 6,666
  • 6
  • 46
  • 69

3 Answers3

4

An answer here solved my problem, but it got deleted for some reason. It was this:

Replacing $('h1').blur() with window.getSelection().removeAllRanges();" fixed it.

iuliu.net
  • 6,666
  • 6
  • 46
  • 69
1

I found this on SO, and should be what you are looking for:

if (window.getSelection) {
    if (window.getSelection().empty) {  // Chrome
        window.getSelection().empty();
    } else if (window.getSelection().removeAllRanges) {  // Firefox
        window.getSelection().removeAllRanges();
    }
} else if (document.selection) {  // IE?
    document.selection.empty();
}

Working fiddle

Community
  • 1
  • 1
Yuri
  • 3,082
  • 3
  • 28
  • 47
0

here is the working code

$(document).ready(function() {
  $('h1').focus();
  document.execCommand('selectAll', false, null);
})

$("#deselect").click(function(){
        window.getSelection().removeAllRanges();
  });

https://jsfiddle.net/v73e3xdf/2/

Mister M
  • 1,539
  • 3
  • 17
  • 37