Search code examples
phpjavascriptjqueryhtmljquery-load

jQuery load() when on a different tab


So I have my load script in jQuery:

function load() {
    $.ajax({
        url: '/urltoload.php',
        cache: false,
        success: function(html){
            //do something
        }
    }

Using a setInterval, how can I check if a user is not on the on the page?


Solution

  • If I have correctly understand your question, you can check if the user "is on" the page and when leave it with the following code:

    $(document).ready(function(){
       $([window, document]).focusin(function(){
          //Your logic when the page gets active
       }).focusout(function(){
          //Your logic when the page gets inactive
       });
    });
    

    Another solution, maybe a little more "intricated", is to check the mouse movements (http://api.jquery.com/mousemove/#fn) each N seconds.

    If you have cross-browsing issue, you can check this answer that gives a good workaround for differents browsers: https://stackoverflow.com/a/1060034/1720344

    UPDATE
    The pseudocode to a timeout function is this:

    setTimeout(function() {
          // Do something after 2 seconds
    }, 2000);
    

    By your comment, I think is best to "around" the sub-function and not the $(document).ready() (I haven't done before, timeouting the document.ready, but you can try and see what it happens ;) - I believe that this function is simple called after N seconds from the document.ready)

    With a timeout of 2 seconds, you can do something like that (but I haven't tested it):

    $(document).ready(setTimeout(function(){
           $([window, document]).focusin(function(){
              //Your logic when the page gets active
           }).focusout(function(){
              //Your logic when the page gets inactive
           });
        }, 2000));