Show a div only once per time the user is on the site

前端 未结 3 1737
天涯浪人
天涯浪人 2020-12-18 11:44

I\'m trying to show a div element only once per time that the user is on the site. I\'ve seen multiple answers to similar questions already, but none of them seem to work...

相关标签:
3条回答
  • 2020-12-18 11:47

    You could use localStorage instead, only when the user clears it out he will get the popup again (same with cookies) but its much simplier:

    (function() {
        var visited = localStorage.getItem('visited');
        if (!visited) {
            document.getElementById("popupp").style.visibility = "visible";
            localStorage.setItem('visited', true);
        }
    })();
    

    html:

    <div id="popupp" style="visibility:hidden;">hi</div>
    

    This way you get a lot of less code. Hope this helps.

    0 讨论(0)
  • 2020-12-18 12:01

    If the goal is to only show it once, you can use the example on the MDN website as a start.

    if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
      alert("Do something here!");
      document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
    }
    

    http://jsfiddle.net/daCrosby/pqb5baa5/

    Edit

    Here it is showing you div. Note, I moved the styling to CSS instead of inline in my jsFiddle - much better approach to get in the hang of

    if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
        document.getElementById("popupp").style.visibility = "visbile";
        document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
    }
    

    http://jsfiddle.net/daCrosby/pqb5baa5/2/

    0 讨论(0)
  • 2020-12-18 12:04

    Try this: in html: class="popupp" change to id="popupp"

    and in javascript: document.getElementById("popupp").style.visibility = visible; change to document.getElementById("popupp").style.visibility = "visible";

    Demo

    0 讨论(0)
提交回复
热议问题