简体   繁体   中英

Unique jQuery popup issue

So I have to have a popup form display once per user session, the client wants it to popup after 10 seconds. If the user navigates to another page on the site, the form still needs to popup and not display after the user closes it on any other part of the site. Here is the jQuery I have written so far.

$(document).ready(function() {
    sessionStorage.setItem('firstVisit', '1');
    if (sessionStorage.getItem('firstVisit') === "1") {
        setTimeout(function() {
            $('.verif').fadeIn('fast');
        }, 1000);
    } else {
        $('.verif').hide();
    }
});

I have the form on each page and right now it just pops up all the time. Am I using the wrong method for the situation? All suggestions are welcome.

Note that the line 2 always sets firstVisit as '1' in session storage. This way, the expression for if will always be true and thus, user will always see the popup.

You need to get the item first, and check its value. Then if it doesn't exist, set it.

$(document).ready(function() {
  var item = sessionStorage.getItem('firstVisit');

  if (!item || item !== "1") {
    setTimeout(function() {
      $('.verif').fadeIn('fast');
    }, 1000);

    sessionStorage.setItem('firstVisit', '1');
  } else {
    $('.verif').hide();
  }
});

Also, using sessionStorage is not a good idea as it is volatile across page refreshes. You, instead, may want to use localStorage for this as you mentioned that this needs to be done for any page.

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