Search code examples
javascriptfocus

Is there any way in JavaScript to focus the document (content area)?


Is there any way to set focus to the document, i.e. the content area, in JavaScript? document.focus() doesn’t seem to do anything.


Solution

  • In HTML 4.01, focus is only discussed in the context of elements such as form controls and links. In HTML 5, it is discussed much more widely. However, how focus works for documents is mostly browser dependent.

    You might try:

    // Give the document focus
    window.focus();
    
    // Remove focus from any focused element
    if (document.activeElement) {
        document.activeElement.blur();
    }
    

    It is very well supported as well.