简体   繁体   中英

How to only allow a popup message to occur on first visit with jQuery

I'm working to include a GDPR-style / Cookie notification for when users visit our site for the first time, but not again until they clear their cache. I have a notification set up to show when the window opens, and a close button to close it.

I've tried using localStorage and sessionStorage jquery, similar to those used to help other users, including hiding the popup first then checking in localStorage to see if it's there:

 $(document).ready(function() {
        $('#toast').hide();
        var element= localStorage.getItem('status');
        if (element == null || element == '') {
            localStorage.setItem('element', 1);
            $('#toast').show();
        }});

But 1) I don't want to copy pasta because 2) it doesn't work.

html for the popup here:

<div id="toast" class="toast-close fixed-bottom" style="background-color: #DB7232; color: white; opacity: .7; margin: 0 0 2rem 2rem; padding: 1rem; width: 18rem;">
     <small>By continuing to browse this site, you're accepting the use of cookies.</small>
     <small><button type="button" data-dismiss="toast" class="close" aria-label="Close">&times</button></small>
</div>

the jquery to close the popup here:

    $(document).on('click', '.toast-close', function() {
        $(this).fadeOut(function(){
           $(this).remove();
        });
    });

I expect when a user comes to our site for the first time (or since we add this feature) the popup will occur; once they x out of either the popup or the browser, the notification will not occur again until their cache is cleared.

The part that you believe you are missing I am unsure of.

Your general code flow: 1) Check for cookie/localstorage 2) Conditionally render popup 3) Set cookie/localstorage if user Consents

I see you have a .hide() before your cookie logic. I'd keep that html fragment somewhere else (display:none?) unless you specifically need it.

It seems like you know how to display/fade it in if you need it.

You are reading 'status', but setting 'element'. Those two names should be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM