Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a browser event for the window getting focus?

Is there a way that when I click on my browser, and give it focus, to run a method once? And then when the browser loses focus and then gets the focus back to again run that method only once, again.

like image 317
Rod Avatar asked Aug 13 '10 16:08

Rod


People also ask

Is focus a window event?

The focus event fires when an element has received focus. The opposite of focus is blur . This event is not cancelable and does not bubble.

How do I know if my browser window has focus?

Use the document. hasFocus() method to check if a window has focus, e.g. if (document. hasFocus()) {} . The method returns a boolean value indicating whether the document or any element in the document has focus.

Which method gets focus on new window?

Window.focus() Method The focus() method is used to focus on the new open window.

What is on focus event?

The onfocus event occurs when an element gets focus. The onfocus event is most often used with <input>, <select>, and <a>. Tip: The onfocus event is the opposite of the onblur event.


2 Answers

You can attach focus and blur event handlers on the window object to track if the window gets or loses focus (see http://jsfiddle.net/whQFz/ for a trivial example). window applies to the current browser context (so that could be a window, a tab, a frame, etc.).

Note : The focus event will fire every time the window gets focus and the blur event will fire every time it loses focus. An example of something that takes focus away from the window is an alert window. If you try to alert in an onfocus event handler you'll get an infinite loop of alerts!

// Set global counter variable to verify event instances var nCounter = 0;  // Set up event handler to produce text for the window focus event window.addEventListener("focus", function(event)  {      document.getElementById('message').innerHTML = "window has focus " + nCounter;      nCounter = nCounter + 1;  }, false);  // Example of the blur event as opposed to focus // window.addEventListener("blur", function(event) {  // document.getElementById('message').innerHTML = "window lost focus"; },  // false); 
like image 124
Daniel Vandersluis Avatar answered Sep 17 '22 00:09

Daniel Vandersluis


$(document).ready(function() { $(window).one("focus", SomeFocusMethod); } );  var SomeFocusMethod = function() {     // do stuff     $(window).one("blur", SomeBlurMethod); }  var SomeBlurMethod = function()  {      // do stuff     $(window).one("focus", SomeFocusMethod);  } 
like image 24
Brett Weber Avatar answered Sep 20 '22 00:09

Brett Weber