2

I want the following code to run only once per visit. If i navigate from homepage to different page and come back to homepage, i should not see the effect again. If i refresh the page, i should see the effect. Here is the code :

function stack(){
       $('#image').animate({
            width: 200,
            height: 150,
            top: 0,

        },1500);
}
$(function(){
    stack();
});

Here is what i am doing : http://jsfiddle.net/kq5M4/

user1761895
  • 37
  • 1
  • 8

3 Answers3

2

Set a cookie that marks that the effect has occurred, but also set a cookie on each page load that keeps track of the last page. If when the home page loads and the last visited page was also the home page, run the effect again.

(Using https://github.com/carhartl/jquery-cookie.)

On the home page:

var lastPage = $.cookie('last_page');
if (!lastPage || lastPage == document.location.pathname)
    stack();

On every page (including home page):

$.cookie('last_page', document.location.pathname, {expires: 0}); // expires: 0 makes it a session-only cookie

You may also need to check the referrer so it will run again if they leave your site and come back later.

Trevor Dixon
  • 17,772
  • 8
  • 66
  • 100
1

on page load, check document.referrer and if is different from your domain or blank, then do the animation. navigating between your pages or refreshing the page will have your domain in document.referrer so you'll skip the animation.

$(function(){
    if (!document.referrer.match(/buybluesky.com/) || document.referrer == document.location.href) {
      stack();
    }
});

Edits: It seems i missed something but I've reedited the code to match all your criterias. Beside checking for the referer to decide if it needs to show or not the animation, it also checks if referrer is equal to the current location. If they are that means it was a refresh since you came to this page from this page.

TheBrain
  • 5,140
  • 2
  • 22
  • 25
1

Use sessionStorage & store the last page:

var visited = sessionStorage.getItem('visit');

if (visited == null || document.location.href == sessionStorage.getItem('lastPage')) {
    stack();
    sessionStorage.setItem('visit', 1);
}

sessionStorage.setItem('lastPage', document.location.href);
KingKongFrog
  • 12,668
  • 17
  • 63
  • 111
  • but what happens if you navigate away or close the browser and come back in a month ? that value will still be there and there will be no animation. – TheBrain Apr 12 '13 at 19:40
  • 1
    @TheBrain `sessionStorage` isn't very persistent. It only lasts as long as the browser is open. This is even better than cookies I think. – Trevor Dixon Apr 12 '13 at 19:54
  • @KingKongFrog, what if they come from another page after visiting this one? `visit` will be 1, but `document.location.href` will equal `lastPage`, unless you add `sessionStorage.setItem('lastPage', document.location.href);` in other pages. You should specify it in your answer. – plalx Apr 12 '13 at 20:23