Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger a 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 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?

like image 733
Jose Avatar asked Oct 31 '22 16:10

Jose


1 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'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>
like image 142
Kishore Sahasranaman Avatar answered Nov 12 '22 18:11

Kishore Sahasranaman