3

I have a JS function that shows a message div on doc ready and then hides it if the 'close' link is clicked.

I would like to show this message div only once per visit to the first page the user visits and then then never for any page view in the site after that.

At the moment when a user clicks on another page within the site, the message div shows again and this is annoying obviously for everyone.

I looked up 'one' in jQuery but am not sure how to implement it with my low JS knowledge.

<script>
$(document).ready(function(){
    $("div#panel").hide();

    var autoTimer = null;

    autoTimer = setTimeout(function(){
        $("div#panel").slideDown("slow");
    },1000);
    $("#close").click(function(){
        $("div#panel").slideUp("slow"); 
        if(autoTimer) clearTimeout(autoTimer);
        autoTimer = null;
        $("div#close").css("display","none");
    });         
});
</script>
antistandard
  • 41
  • 1
  • 1
  • 6
  • 6
    `.one()` does not provide uniqueness across page loads. Set a cookie, use `localStorage`, or something else which does persist across page loads. – Matt Ball Jul 08 '13 at 20:19
  • you need to store that info `either on server` , `local storage` or `a session`. As web is stateless and it cannot remember anything after a page refresh – Sushanth -- Jul 08 '13 at 20:19

5 Answers5

9

Create a localStorage key, set it when the user gets to the page, and remove it when the user leaves the page:

//On user coming to page:
//Check localStorage on each page visit, if it's null, show your div
if (!localStorage.getItem("visited")) {
    //show the div

    //Set the key
    localStorage.setItem("visited", "true");
}

//clear localStorage on tab close
window.onbeforeunload = function() {
    localStorage.removeItem("visited");
};
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Hello, Thank you for your help. I have updated the question a little as it was a little confusing when I re-read it. The line I changed was: "I would like to show this message div only once per visit to the first page the user visits and then then never for any page view in the site after that." – antistandard Jul 08 '13 at 20:36
  • @user2562000 if you check my answer, that's what mine does. – ryandawkins Jul 08 '13 at 20:39
4

I had a similar issue where I wanted to show a message box once the user hovers over a particular div. I used the local Storage as follows:

$(function() {
    //set a variable <visited=false> in localStorage on page load
    localStorage.setItem("visited", "false");
    //once the mouse is hovered over the <maindiv>
    $(".maindiv").mouseenter(function(){
         //get the variable value from local storage and compare it
        var visit=localStorage.getItem("visited");
        if(visit==="false")
        {
            $(".slide-msg").show();
            //set visited to true 
            localStorage.setItem("visited","true");
        }
    });
});
Irshad
  • 1,016
  • 11
  • 30
  • You should check if the localStorage exists, THEN set it to false, otherwise you're setting false on every refresh / load of the page. ```if (!localStorage.getItem("visited")) { localStorage.setItem("visited", "false"); }``` – Andrew Lazarus Apr 02 '15 at 10:57
  • Yes. You are right. But for my requirement, it was for a single page app so i wanted user to go to the start of UseCase on a refresh or close. But thank you )) – Irshad Apr 04 '15 at 10:52
2

I have personally used this:
https://github.com/js-cookie/js-cookie
As so:

//import main js to use this method:
<script src="js/js.cookie.js"></script>
$(document).ready(function(){ 
    //if visited cookie does not equal true, so its first visit:
    if(Cookies.get('visited') != 'true') {
        console.log("first visit");
        //after doing what we want on first visit, we set cookie to true
        Cookies.set('visited', 'true', { expires: 7 });
    } else {
        //so if first visit cookie is true, we do the following:
        console.log("not first visit");
    }
});

I havn't tried it but thers also a jquery version:
https://github.com/carhartl/jquery-cookie
I found out about both methods from:
http://www.electrictoolbox.com/jquery-cookies/
A link posted from a similar question:
https://stackoverflow.com/a/8757487/4651567

Community
  • 1
  • 1
OB7
  • 625
  • 1
  • 7
  • 11
1

This will be persistant as long as the web browsers cache is not cleared.

Here is my reference link: http://www.w3schools.com/html/html5_webstorage.asp

You could try this:

$(document).ready(function(){
    // Checks to see if it is the first visit on browser open
    if(sessionStorage.firstVisit != true) {
        // Stores visit
        sessionStorage.firstVisit = true;
        $('#panel').show();
    } else {
        $('#panel').hide();
    }
    $("#close").click(function(){
        $("#panel").hide();
    });  
});

The session storage will stay loaded per visit to the website.

An alternate solution would be to keep it based on forever, so if you want them to only see it if it's their very first time to visit the website from that machine:

$(document).ready(function(){
    // Checks to see if it is the first visit on browser open
    if(localStorage.firstVisit != true) {
        // Stores visit
        localStorage.firstVisit = true;
        $('#panel').show();
    } else {
        $('#panel').hide();
    }
    $("#close").click(function(){
        $('#panel').hide();
    }); 
});
ryandawkins
  • 1,537
  • 5
  • 25
  • 38
  • Hello, Thank you for your help. I have updated the question a little as it was a little confusing when I re-read it. The line I changed was: "I would like to show this message div only once per visit to the first page the user visits and then then never for any page view in the site after that." – antistandard Jul 08 '13 at 20:41
  • Cool, sorry. I couldn't get it to work, not saying it doesn't work, I just can't make it work. – antistandard Jul 08 '13 at 20:57
  • What is your problem with it? Meaning, what's your console output? – ryandawkins Jul 08 '13 at 20:58
  • no errors in the console. just doesn't stop the message div from showing when I navigate to another page. the page in question is: http://antistandard.com/journal/ – antistandard Jul 08 '13 at 21:11
  • I wish I could show you my new code that I made from your snippet but this message box won't allow so many characters. Sorry I am new to stack overflow. – antistandard Jul 08 '13 at 21:11
  • Does your browser support local storage? – tymeJV Jul 08 '13 at 21:52
  • @user2562000 You can try a pastebin snippet at pastebin.com – ryandawkins Jul 09 '13 at 13:48
0

If you use session storage, you can set a value to determine if a certain page has be visited during that session. But since this is an HTML 5 feature you'll still need to use cookies to handle IE.

<html>
<body onload="bodyOnload()">
<div id="test" style="width: 100px; height: 100px; background: blue;">First Page View</div>
<input type="button" value="Delete Cookie" onclick="deleteCookie()"/>
<script>
// 'Delete' cookie for testing
function deleteCookie()
{
if(typeof(Storage) !== "undefined"){
    sessionStorage.returnVisit = "false";
    console.log("sessionStorage set.");
}
else{
    setCookie("return_visit","false",1);
}
}

//W3 Schools setCookie function
function setCookie(c_name,value,exdays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
  document.cookie = c_name + "=" + c_value;
}

//W3 Schools getCookie function
function getCookie(c_name)
{
  var c_value = document.cookie;
  var c_start = c_value.indexOf(" " + c_name + "=");
  if (c_start == -1)
  {
    c_start = c_value.indexOf(c_name + "=");
  }
  if (c_start == -1)
  {
    c_value = null;
  }
  else
  {
    c_start = c_value.indexOf("=", c_start) + 1;
    var c_end = c_value.indexOf(";", c_start);
    if (c_end == -1)
    {
      c_end = c_value.length;
    }
  c_value = unescape(c_value.substring(c_start,c_end));
 }
return c_value;
}

//Check return_visit cookie on page load
function bodyOnload()
{
if(getCookie("return_visit") === 'true' || sessionStorage.returnVisit === "true"){
    //Do something if user has already visited page
            var test = document.getElementById("test");
    test.innerHTML = "Welcome Back";
    test.style.background = "red";
}
else
{
    if(typeof(Storage) !== "undefined"){
        sessionStorage.returnVisit = "true";
        console.log('Session Storage set.');
    }
    else{
        setCookie("return_visit","true",1);
    }
}
}

</script>
</body>
</html>
ExceptionLimeCat
  • 6,191
  • 6
  • 44
  • 77