Trigger an event when the user is on the page

I have this code

$(document).ready(function(){ var fade_in = function(){ $(".quote").fadeIn(); } setTimeout(fade_in, 2000); var fade_out = function() { $(".quote").fadeOut(); } setTimeout(fade_out, 10000); }); 

What he does is that the div "quote" slowly disappears, remains for a few seconds, and then disappears. I want all this to happen when the user is on the page, if you are not on the page, the text disappears, disappears, and you skip it. How can i do this?

+5
source share
2 answers

There are two ways:

First: (bit old)

 $(document).ready(function() { window.onfocus = function() { var fade_in = function() { $(".quote").fadeIn(); } setTimeout(fade_in, 2000); var fade_out = function() { $(".quote").fadeOut(); } setTimeout(fade_out, 10000); }; }); 
 <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="quote">quote</div> 

Second:

 function getHiddenProp() { var prefixes = ['webkit', 'moz', 'ms', 'o']; // if 'hidden' is natively supported just return it if ('hidden' in document) return 'hidden'; // otherwise loop over all the known prefixes until we find one for (var i = 0; i < prefixes.length; i++) { if ((prefixes[i] + 'Hidden') in document) return prefixes[i] + 'Hidden'; } // otherwise it not supported return null; } function isHidden() { var prop = getHiddenProp(); if (!prop) return false; return document[prop]; } // use the property name to generate the prefixed event name var visProp = getHiddenProp(); if (visProp) { var evtname = visProp.replace(/[H|h]idden/, '') + 'visibilitychange'; document.addEventListener(evtname, visChange); } function visChange() { var txtFld = document.getElementById('visChangeText'); if (txtFld) { if (!isHidden()) { var fade_in = function() { $(".quote").fadeIn(); } setTimeout(fade_in, 2000); var fade_out = function() { $(".quote").fadeOut(); } setTimeout(fade_out, 10000); }; } } } 
 <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="quote">quote</div> 
+2
source

This will be done when the page is visible.

 $(document).ready(function(){ $( "div:visible" ).click(function() { $( this ).css( "background", "yellow" ); }); }); 
0
source

Source: https://habr.com/ru/post/1235481/


All Articles