Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire javascript every x page load, for example, every 3rd page

Tags:

javascript

I'm sure this question has been answered, before, but my searches are coming up empty.

I have a simple jQuery function (that slides in a box after the page has been scrolled down). It works fine.

However, how do I set cookies, or other method, to make it execute on the first page load and, then, on every 3rd page load of the session, after that?

like image 729
Leora Deans Avatar asked Sep 06 '25 04:09

Leora Deans


1 Answers

A little snippet like this should work for you.

(function () {
  // Get the countdown from localStorage
  var countdown = Number(window.localStorage.getItem('countdown'));
  
  // If countdown isn’t set it or if it has
  // run a couple times it’ll be `0`
  // Either way—we reset countdown and run the function
  if (!countdown) {
    countdown = 3;
    // Run the function
  }

  // Update the countdown
  window.localStorage.setItem('countdown', countdown - 1);
})();
like image 185
Alexander Avatar answered Sep 08 '25 19:09

Alexander