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
achieved?

My code is as below.

$(document).ready(function() {
  if($(".happening").length > 1 ) { 
             $(".happening-switch").click(function () {
				 $(".happening:visible").hide().next().show();  
				 
});
   }});


$(document).ready(function() {
   if($(".happening").length < 2 ) { 
             $(".happening-switch").click(function () {
				 $(".happening:visible").slideUp();          
  });
  
 
		 
   }});

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:

if($.cookie('happening')){...}

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.

.

$(function(){
	/**
	 * Close the box everywhere
	 * - Creates a cookie, "alert-closed" accessible everywhere
	 * - Cookie lasts until the session is ended (user closes the browser etc)
	 *
	 * @see  https://github.com/carhartl/jquery-cookie#usage
	 */
	function closeBox(){
		$('.happening').slideUp()
		$.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
	if($.cookie('alert-closed')){
		console.log('Closing the alert box automatically...');
		closeBox()
	}
	// Close the box on click
	$('.happening-switch').click(function(){
		console.log('Closing the alert box manually...');
		closeBox()
	})
})

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.