Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 215
Timwi Avatar asked Aug 07 '11 23:08

Timwi


People also ask

How do you focus in JavaScript?

JavaScript | Focus()JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.

How do you focus a particular part of the HTML page in JavaScript?

The focus() function can be used to focus a particular part of the HTML page in JavaScript.

What is window focus in JavaScript?

Window focus() The focus() method sets focus to a window. The blur() method removes focus from a window.

Can you focus a div?

Yes - this is possible. In order to do it, you need to assign a tabindex...


2 Answers

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.

like image 111
RobG Avatar answered Sep 20 '22 07:09

RobG


It seems that the following code works...

document.activeElement.blur(); 
like image 39
Timwi Avatar answered Sep 20 '22 07:09

Timwi