Only Displaying Dialog Box on First Load

点点圈 提交于 2019-12-11 06:27:13

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/44051731/only-displaying-dialog-box-on-first-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!