Only show jQuery once per session

余生长醉 提交于 2019-12-31 05:36:28

问题


So I use the following code to show and fade an element. I have set the div on visible on the homepage and hidden on all other pages so the div only shows up on the homepage. My problem is, everytime I visit the homepage, the div will show up. Instead I would like to show the div only once per session. I've tried to fix it with cookies but it didn't work.

$(window).load(function(){
$("#testlay").fadeIn('slow').delay(1000).fadeOut(1600);
});

回答1:


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);
      }
    });



回答2:


You can use localStorage which would be more right in this case IMO.

$(window).load(function(){
    if(typeof localStorage.testlayHidden != 'undefined') {
        $("#testlay").fadeIn('slow').delay(1000).fadeOut(1600, function() {
            localStorage.testlayHidden = 1; 
        });
    }
});


来源:https://stackoverflow.com/questions/41344630/only-show-jquery-once-per-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!