KyleMassacre Posted April 3, 2015 Posted April 3, 2015 Ok, so basically I have an ajax call that I am making on a timeout and I only want it to work initially when the page loads and if the browser/tab is actually active. So in other words the call does not get made if you are in another tab or you open up another program. Unfortunately I am on my phone right now and can't post any snippets worth anything but here I go with some major stuff: $([window,document]).ready(function() { //not really sure this is right either for what I want. I read it's for X-Browser myFunction();//Inital call because it displays data function myFunction() { $.ajax({ //non important }).done({ //makes the data display in the header }).success({ //this is where I want to check if the browser window/tab is in focus and there is a timeout function here that calls myFunction again }); } }); The problem I have is that by default the window/tab is not in focus on default and the only way to get it to work is if I go to another tab and switch back then it will start, and the other issue is I need it to stop if it's out of focus again. I looked online and tried pretty much everything I can find on this and nothing worked like I wanted. So if you have some tips I would greatly appreciate it. P.S. I know I'm missing some function()'s here and there so that's not the issue Quote
lucky3809 Posted April 3, 2015 Posted April 3, 2015 I don't know if this is what you mean, but maybe it is... http://www.thefutureoftheweb.com/blog/detect-browser-window-focus Quote
Coly010 Posted April 3, 2015 Posted April 3, 2015 I wouldnt say I know a lot of jQuery but I ran across a similar problem in one of my other projects. Initially, for this to work I believe, you need to have a function that sets your timeout. Eg. $(document).ready(function() { var myTimeout; var ajaxSuccess = 0; myFunction(); //Inital call because it displays data function setMyTimeout() { myTimeout = setTimeout(myFunction(), 1000); } function myFunction() { $.ajax({ //non important }).done({ //makes the data display in the header }).success({ ajaxSuccess = 1; }); } if(ajaxSuccess == 1){ $(window).focus(function() { if (!myTimeout){ setMyTimeout(); } }); $(window).blur(function() { clearTimeout(myTimeout); }); } }); That is completely untested, it may work, but at the very least I hope it gives you something to think about Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.