www.webdeveloper.com
Results 1 to 4 of 4

Thread: Detect window focus

  1. #1
    Join Date
    Apr 2004
    Posts
    13

    Detect window focus

    How can I detect when a window is out of focus?

    Basically, I'm coding a chat application, and woul like to detect when a user's window is out of focus so I can play an alert sound.

    I have tried

    if(window.blur) and
    if(!window.focus)

    Non of these worked. They always return true, because I understand they simply check if the browser supports blur and focus.

    TIA.

  2. #2
    Join Date
    Nov 2002
    Posts
    4,473
    You would code an event for the window. For example:
    Code:
    window.onblur = function () {
     // place your code here
    }

  3. #3
    Join Date
    Apr 2004
    Posts
    13
    Thanks gil,

    I don't want an event to be triggered as soon as the window loses focus. Rather I need to find out at any time if the window is out of focus as a condition for taking some action.

    Maybe I just don't follow your logic.

    If I do

    window.onblur = function myfunc() {
    // place your code here
    }

    Is it correct for me to say that myfunc() would only be available if the window is out of focus? And that myfunc() disappears as soon as the window gains focus again?

  4. #4
    Join Date
    Nov 2002
    Posts
    4,473
    Is it correct for me to say that myfunc() would only be available if the window is out of focus? And that myfunc() disappears as soon as the window gains focus again?
    It is always available. It is just sitting there waiting for the window to lose focus. The function runs one time when the window loses focus. The window must regain focus and then lose it again for the fuction to run again.

    I don't know what you mean by the function "disappears".
    I don't want an event to be triggered as soon as the window loses focus. Rather I need to find out at any time if the window is out of focus as a condition for taking some action.
    There are no such properties avaliable, only the events. You could make your own variable and set it when the event occurs:
    Code:
    window.onblur = function () {hasFocus = false;}
    window.onfocus = function () {hasFocus = true;}
    However, you cannot sit in a loop watching hasFocus because it will take up all the processing time and nothing else will be allowed to happen. You have to adjust your thinking such that the blur event makes something happen and then the focus event makes something else happen.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles