简体   繁体   中英

Only Displaying Dialog Box on First Load

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" );
        }
      }
    }); 
  });

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
  });

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

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