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 it does is that the div "quote" slowly fades in, stays for a few seconds and then fades out. What I want is that all this happens when the user is on the page, if you're not in the page,the text fades in, fades out and you miss it. How can I do that?
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's 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With