Search code examples
javascriptjqueryfirefoxsetfocus

Force set focus back to contenteditable document in Firefox


Works In all browsers except Firefox

function editorFocusLost(event) {
    // Trying to set focus back
    setTimeout(function() {
        $editorBody[0].focus();
    }, 4);
}
// Listen for focus lost event
$editorBody[0].addEventListener('DOMFocusOut', editorFocusLost, false);

I tried also some different events like 'focuslost', 'blur', 'DOMFocusOut', but it doesnt works in Firefox. But we can solve problem with blur through workarounds. Yet main problem to set the focus back $editrBody[0].focus() also does not firing in Firefox

https://jsfiddle.net/mm1mbqto/1/


Solution

  • DOMFocusOut event does not work in firefox; you have to use blur event.

    The only issue is focusing initially, in firefox the focus is initially not set to contenteditable, This might be due to issue with jsfiddle itself. I tried in jsbin and worked fine.

    (function($) {
    
      var $body = $('.editor');
      $body[0].focus();
    
      function editorFocusLost(event) {
        setTimeout(function() {
          $body[0].focus();
        }, 4);
    
      }
      $body[0].addEventListener('blur', editorFocusLost, false);
    
    })(jQuery);
    .container {
      margin: 0 auto;
      width: 100%;
      padding: 50px;
    }
    .editor {
      width: 300px;
      height: 100px;
      background-color: #fff;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div class="container">
      <label for="">Editor</label>
      <div class="editor" contenteditable="true"></div>
      <input>
    </div>