DCJones DCJones - 2 months ago 19
jQuery Question

Jquery modal popup display only once per user session

I have a jquery function that displays a modal popup when the page loads. Is there a way so it only displays once per user session. I have rad many posts but for whatever reason I can't get them to work in my script.

my script:

$(document).ready(function() {

$(window).load(function(){
$( "#dialog1" ).dialog();
});

});


The modal popup is made up of:

<div id="dialog1" title="IMPORTANT!">
<div class="imaindateselleft_padding_right_red">Content here</div>
</div>


Mant thanks in advance for your time and help.

Answer

One way to achieve this is to integrate with cookie. Let it display the dialog and store the value that the dialog has been shown in the cookie so it won't be displayed next time.

And in this approach, I am using jQuery Cookie. (Feel free to use vanilla javascript to r/w cookies). And I also assume you use jQuery UI to call dialog.

$(document).ready(function() {
    var dialogShown = $.cookie('dialogShown');

    if (!dialogShown) {
        $(window).load(function(){
            $( "#dialog1" ).dialog();
            $.cookie('dialogShown', 1);
        });
    }
    else {
        $("#dialog1").hide();
    }
});

What the code above does, is simply to set the cookie once the dialog has been popped before. The only way to let the same user to see the dialog again is when the cookie expires (which you can set), or the user clears the cookies.

Edit: Second way to achieve this, you can use your localStorage if the browser supports it.

$(document).ready(function() {
    var dialogShown = localStorage.getItem('dialogShown')

    if (!dialogShown) {
        $(window).load(function(){
            $( "#dialog1" ).dialog();
            localStorage.setItem('dialogShown', 1)
        });
    }
    else {
        $("#dialog1").hide();
    }


});