/

HTML / CSS / JavaScript Tutorial

JavaScript Window method: focus()

[this page | pdf | back links]

The focus() method (when applied to Window objects in the JavaScript BOM) sets focus to the window, which typically brings the window to the foreground (although this may not work as expected in all browsers depending on what settings the user has adopted).

 

It has the following syntax with no parameters. It does not return a value.

 

window.focus(message)

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
try clicking on this button (it should open a new window that has focus)<br><br>
<button onclick="myOnclick()">Example</button>

<script>
function myOnclick() {
  var newWindow = window.open("","", "width=300, height=300");
  newWindow.document.write("<h3>A new window</h3>");
  newWindow.focus();
}
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodWindowFocus() {
  return !!window.focus;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile