How to Trigger a Jquery Function Only Once in One Page, Per Session

How to trigger a jquery function only once in one page, per session?

Javascripts sessionStorage can make this possible.

This sessionStorage-variable will only be accessible while and by the window that created it is open. So, after closing the window, the sessionStorage variable will be undefined.

You can simply create this by using something like sessionStorage.firstVisit = 1.

Simple wrap this in an if-statement to check whether to show the animation or not.

For more info on this check http://www.w3.org/TR/webstorage/#the-sessionstorage-attribute

JQuery - Run once per session

If you want to execute this line only once per browser session you can use sessionStorage. When you set a variable on sessionStorage it keeps its value until the browser closes (e.g. until you close Google Chrome).

So you can do something like:

if (!sessionStorage.alreadyClicked) {
$('.popup-with-form').magnificPopup('open');
sessionStorage.alreadyClicked = 1;
}

Be careful with sessionStorage because it can only store string values.

If you want the line to be executed only once per page session (which means once every page refresh) then you can use any variable and set it to true to remember you already executed the line:

if (!window.alreadyClicked) {
$('.popup-with-form').magnificPopup('open');
alreadyClicked = true;
}

Only show jQuery once per session

You can use coockie for this take a look at below example hope it helps

Please find this fiddle for the same

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires=" + date.toUTCString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}
//your window load function replace with below
$(function(){
if(readCookie('CodefireOnce') == null)
{
createCookie('CodefireOnce','true',7);
$("#testlay").fadeIn('slow').delay(1000).fadeOut(1600);
}
});

Send event only once per session?

Google Analytics events are a hit type (like pageviews) which can not be scoped to sessions or users. Even if you could only send one event per session (using either cookies or sessionStorage, you wouldn't actually get the whole picture in your GA reports.

To offer a better solution, consider using a Custom Dimension with a scope of "session" to store that data. What's cool about this is that the dimension is applied to all hit types within the scope- meaning any pageview, event, etc. also has the dimension associated with it.

To do this, create the dimension in Google Analytics Admin under the Property settings within Custom Definitions. Get the index number (a string that looks like 'dimension1' or 'dimension 4') and paste the line BEFORE sending the pageview (ideally) or an event.

Remember: Dimensions are not hits, so simply setting them does nothing until a hit is also sent! Also, be sure to enable non-interaction on the events (if that is the route you choose) or else you will be misreporting bounces from those using Ad Blockers.

Here is the ideal snippet (Note: if you are going to setTimeout as part of your detection, do not use this method as it would delay the pageview send too... Consider a method that doesn't need a timeout.):

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');

//Detection goes here. If true:
ga('set', 'dimension1', 'Ad Blocker'); //Change 'dimension1' to yours.

ga('send', 'pageview');
</script>

Your code from above would look like this if you can't do the detection before the <head> GA send pageview snippet.

function test(){
var len = $('.ad').length;
if(len === 0){
ga('set', 'dimension1', 'Ad Blocker'); //Change 'dimension1' to yours.
ga('send', 'event', 'Ad Blocker', {nonInteraction: true}); //Add action and label as needed.
}
}

Run Jquery slideDown only once per session

Since you've already mentioned sessionStorage, it's pretty easy to use it to save a flag that tells you if the slideDown already happened or not. Then you can use that flag to make sure it doesn't happen again.

Inside you slide down code:

// perform the slide down only if the slide down flag wasn't set
if(sessionStorage.getItem('hasSlideDown') !== 'yes') { // check if slide down flag was set
sessionStorage.setItem('hasSlideDown', 'yes'); // set the slide down flag
$('#notification_toolbar').slideDown(); // perform the slide down
}

How sessionStorage works:

A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

Show preloader only once per session

Please try this

jQuery(window).load(function() {
if (sessionStorage.getItem('dontLoad') == null)
{
jQuery("#status").delay(3000).fadeOut("slow");
jQuery("#preloader").delay(3000).fadeOut("slow");
sessionStorage.setItem('dontLoad', 'true');
}
});

The sessionStorage property allows you to access a session Storage object. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

FIDDLE DEMO

Run JQuery function just once per visit

You can store the time of the visit in localStorage and just check it.

var now = (new Date()).getTime();
var lastTime = 0;
var lastTimeStr = localStorage['lastTime'];
if (lastTimeStr) lastTime = parseInt(lastTimeStr, 10);
if (now - lastTime > 24*60*60*1000) {
// do animation
}
localStorage['lastTime'] = ""+now;

EDIT : I made a fiddle demonstrating it :

http://jsfiddle.net/dystroy/jAjLB/

You'll see the animation the first time, but not the second one, except if you wait for one minute (you could set it to a few hours for your site).



Related Topics



Leave a reply



Submit