How would I get a notification bar to display only

2019-06-03 09:02发布

问题:

I have a notification bar that I only want to display once per session, or possibly not have the notification display for a predetermined amount of time. I am using session storage but unfortunately I cant get it to work correctly.

Thanks

Here is my code ----------->

    <script>
$(document).ready(function() {

            var $alertdiv = $('<div id = "alertmsg"/>');
            $alertdiv.text("Join our email list and receive the latest updates at 3Elements Review.");
            $alertdiv.bind('click', function() {
                $(this).slideUp(200);
            });
            $(document.body).append($alertdiv);
            $("#alertmsg").fadeIn("slow"); 
            setTimeout(function() { $alertdiv.fadeOut(400) }, 6000);
                            });

$(window).load(function(){
        if(typeof(window.sessionStorage) != 'undefined') {
        $("#alertmsg").val(window.sessionStorage.getItem('mySessionVal'));
            window.sessionStorage.setItem('mySessionVal', $("#alertmsg").val());
            window.sessionStorage.setItem('storedWhen', (new Date()).getTime());
    }
});
</script>

回答1:

There's no apparent reason to use window.onload for sessionStorage, DOM ready should suffice ?

Also, you need to check if the value exists in the storage before displaying the message, otherwise the message will always show :

$(document).ready(function() {
    if (typeof window.sessionStorage != undefined) {
        if (!sessionStorage.getItem('mySessionVal')) {
    //          ^^^ you can check time here as well ?
            $('<div />', {
                id   : "alertmsg",
                text : "Join our email list and receive the latest updates at 3Elements Review.",
                on   : {
                    click: function() {
                        $(this).slideUp(200);
                    }
                }
            }).appendTo('body').fadeIn("slow").delay(6000).fadeOut("slow");
            sessionStorage.setItem('mySessionVal', true);
            sessionStorage.setItem('storedWhen', Date.now());
        }
    }
});

FIDDLE