0

How can I execute this function only once and when the browser tab/window is active ?

$(function(){

noty({text:'Here is my text',type:'error'});

return false;
});

If I use:

$(window).one('focus', function(){

The function is executed but only if I leave the tab and come back again.

Any ideas ?

Many thanks

  • Perhaps, it may help https://stackoverflow.com/questions/1760250/how-to-tell-if-browser-tab-is-active – Sergey Oct 16 '17 at 18:13

2 Answers2

0

What do you mean by 'is active' ?

If you need this function to be called just one time after load, you can use load event or ready with jquery.

If it's every time the tab is active, so when your user is on the tab, and the mouse focus your document, you can use the focus event.

let activated = false;
window.addEventListener('focus', function() {
    if(!activated) {
        console.log('test');
        activated = true;
    }
})
sheplu
  • 2,937
  • 3
  • 24
  • 21
  • Hi sheplu, what I need is to show the function if the window is active. And if you open a new window/tab the function does not appear until you go to the tab. – Playinteractive Oct 16 '17 at 18:18
  • ok so you need to trigger the function only once when the user come in your page. Then you could use focus, with a if case to check if it's the first time your use come on the website – sheplu Oct 16 '17 at 18:20
  • I sheplu, if I refresh the window doesn't work! Is it possible work with 'load' and 'focus' ??? – Playinteractive Oct 16 '17 at 19:20
  • if you refresh it will work, but only when you will click on the window. If you want to trigger the function when the user move the mouse (on your window), you can change the event to `mouseover` I don't think there is an `active` event. and `load` will be trigger when the page is loaded, even if you are not on the tab – sheplu Oct 16 '17 at 19:40
  • Sorry sheplu but this is not exactly what I'm looking for. I'll try to explain again. What I really need is something like YouTube player: if you open a new tab the video does not start until you click on this new tab. But If you are in the current tab and you refresh the window, the video starts. – Playinteractive Oct 16 '17 at 22:56
  • you need to see if there is a better event or maybe try to combine two events. I see what you want to do, but like with youtube it depend of your browser. Chrome wait you to go on the page before starting the video, firefox does not. I will try few things tomorrow – sheplu Oct 16 '17 at 23:00
0

If you use the load event it will fire when the page is loaded.

$(document).ready(() => {
  $(window).on('load', () => {
    noty({ text: 'Here is my text', type: 'error' });
  });
});
kemotoe
  • 1,730
  • 13
  • 27
  • Hi kemotoe, if I open a new window/tab the function is executed although the tab is active or not... I only want to be executed if the tab is active. – Playinteractive Oct 16 '17 at 18:25