Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox - focusing a paragraph inside contenteditable

Firefox doesnt seem to set focus on paragraph inside contenteditable. I event tried to set the focus programatically. Chromes seems to do some magic and everything works fine.

<h2 contenteditable="true">Some text</h2><br/><br/>
<div contenteditable="true">
  <p id="test">Paragraph text</p>
</div>
  1. Click on h2 and hit tab
  2. start typing - The text does not appear inside P.

JSFiddle - http://jsfiddle.net/THPmr/126/

$( "#test" ).focus(function() {
  $( "<span>Focused!</span>" ).appendTo( "body" ).fadeOut( 1000 );
});

$("#before").on('keydown', function(e){
            if(e.which == 9){
                $('#test').triggerHandler('focus');
            }

        });

$("#test").bind( "focus", function() {
   $("#test").css('background', 'yellow');   
});

I also tried to set the caret position but it doesnt work in firefox, works in chrome

JSFiddle - http://jsfiddle.net/vXnCM/2998/

function setCaret() {
    var el = document.getElementById("test");
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(el, 0);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    el.focus();
}

Thanks in advance

like image 688
Coder Avatar asked Jul 24 '14 06:07

Coder


1 Answers

Well, I don't have any official Firefox info, but when I merged your two jsfiddle examples together, I was able to get the caret in the right place. This seems to work well for me in Firefox 30 on Mac OSX 1.9.4. I was able to recreate the exact original problem by simply commenting out the call to setCaret().

Merged JSFiddle

One thing I changed while merging the code was to move the element focus to happen before all of the range manipulation, but I'm not certain that has any impact.

like image 62
TLS Avatar answered Oct 05 '22 23:10

TLS