Only Displaying Dialog Box on First Load

2019-07-30 14:41发布

I currently have a dialog box that automatically displays each time the page is loaded. However, I have functionalities such as a search so when a user searches for an entry, it will then display the popup box again since the page is being loaded again.

How can I get it so that the dialog box only displays the first time the page is loaded?

Here is my HTML code for the dialog box:

<!-- Dialog box -->
<div id="dialog-form" title="Instructions">
  <form>
    <fieldset>        

      <ul>
          <li>These are instructions</li><br>
          <li>that should be displayed</li><br>
          <li>inside the dialog box</li><br>
          <li>on the first load only</li>
      </ul>

    </fieldset>
  </form>
</div>

JavaScript:

$( function() {   

    var dialog = $( "#dialog-form" ).dialog({
      autoOpen: true,
      height: 400,
      width: 350,
      modal: true,
      buttons: {
        OK: function() {
          dialog.dialog( "close" );
        }
      }
    }); 
  });

2条回答
萌系小妹纸
2楼-- · 2019-07-30 15:12

You can use sessionStorage.

When first time you show the popup, mark this in browser's sessionStorage by setting some value using sessionStorage.setItem("variableName", "value");.

Now, add a check before you show the popup that checks whether that value is already set in browser's sessionStorage by using sessionStorage.getItem("variableName");.

sessionStorage keeps variables in browser's memory until you close the browser tab/window. So, it works fine across page loads.

$( function() {   
    var popupDisplayed = sessionStorage.getItem("popupDisplayed");
    if( popupDisplayed !== "true" ){
    var dialog = $( "#dialog-form" ).dialog({
      autoOpen: true,
      height: 400,
      width: 350,
      modal: true,
      buttons: {
        OK: function() {
          dialog.dialog( "close" );
        }
      }
    });

    // mark this in sessionStorage
    sessionStorage.setItem("popupDisplayed", "true" );
   }//if not found in sessionStorage
  });
查看更多
闹够了就滚
3楼-- · 2019-07-30 15:21

Edit:

If you need to do only for one session, use SessionStorage as described by Mohit.

If it should be stored permanently in the user's browser, use LocalStorage

Use Local Storage to check if a popup has been shown or not.

$(document).ready(function() {
    var isshown = localStorage.getItem('isshown');
    if (isshown== null) {
        localStorage.setItem('isshown', 1);

        // Show popup here
        var dialog = $( "#dialog-form" ).dialog({
        autoOpen: true,
        height: 400,
        width: 350,
        modal: true,
        buttons: {
         OK: function() {
         dialog.dialog( "close" );
         }
       }
     }); 
    }
});

This will show popup only once

More info on using Local Storage is Here

查看更多
登录 后发表回答