jkupczak
jkupczak

Reputation: 3031

Fire jquery script on first page load, and then never again for that user?

I'm using this jQuery Modal Window script on my site: http://www.zurb.com/playground/reveal-modal-plugin

It currently activates a Modal Window when the user clicks on a link. However, I want to modify it to automatically run once the page is loaded for the first time. But subsequent visits to that same page by that same user will not activate the script again. I could probably figure out how to get it to run on page load myself. But getting it to only fire one time, and then never again is something I'm not familiar with.

Any help would be greatly appreciated.

Upvotes: 0

Views: 2483

Answers (1)

moribvndvs
moribvndvs

Reputation: 42497

You would need something persistent in that client's browser, or if this is a web application where the user has a profile, you'd need to track the state on the server side.

If you're doing it all client side, you'd likely use a cookie. You can either set the cookie from the server side, or in JavaScript.

Here are some set cookie/get cookie functions:

function setCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function getCookie(cookieName) {
 var theCookie=" "+document.cookie;
 var ind=theCookie.indexOf(" "+cookieName+"=");
 if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
 if (ind==-1 || cookieName=="") return "";
 var ind1=theCookie.indexOf(";",ind+1);
 if (ind1==-1) ind1=theCookie.length; 
 return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
}

So, you would tie it together like this:

$(function() {

     var skipModal = getCookie('skipModal');
     if (!skipModal) { // check and see if a cookie exists indicating we should skip the modal
         // show your modal here


         setCookie('skipModal', 'true', 365*5); // set a cookie indicating we should skip the modal
     }
});

Upvotes: 3

Related Questions