Retain function action all through website[Solved]

Trying to retain the action of the function below in all the pages.
Example: If the user closes the alert box, let it “alert box” stay closed on
all pages except if the user closes the browser and comes back. I tried local storage but that didn’t work out well. How can this be

My code is as below.

$(document).ready(function() {
  if($(".happening").length > 1 ) { 
             $(".happening-switch").click(function () {

$(document).ready(function() {
   if($(".happening").length < 2 ) { 
             $(".happening-switch").click(function () {

Try cookies, jQuery Cookies is a great library.

Basically, on your click event, add something like:

$.cookie('happening', true)

And then on page load, check if that cookie is present before running the code:


What happened?

I haven’t used cookie before. How do I add that to my function?

The alert closes on its own when you switch pages or when you refresh it.

Can you provide an example?

This should get you going, you might need to change the jQuery selectors though.


	 * Close the box everywhere
	 * - Creates a cookie, "alert-closed" accessible everywhere
	 * - Cookie lasts until the session is ended (user closes the browser etc)
	 * @see
	function closeBox(){
		$.cookie('alert-closed', true, {path: '/'})
		console.log('Alert box closed.');

	// Close the box if the user closed it this session
	// - Simply checks the alert box above
		console.log('Closing the alert box automatically...');
	// Close the box on click
		console.log('Closing the alert box manually...');

Open up your console. You should see these messages:

  1. Nothing on your first visit
  • “Closing the alert box manually…Alert box closed.” when you click on the close button

  • “Closing the alert box automatically…Alert box closed.” when you visit any other page

  • .#1-3 when you close the tab/browser and open it back up again

Thanks Labofoz. I’ll try it out right away.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.