简体   繁体   中英

Reloading the page only once on a button click

I have a Load button and I am calling onclick event on that button which would refresh the page using window.location.reload() . But ,what I want is that the reload should only be called when the button is clicked for the first time . From the second click and till the HTML page is active the reload should not be called .

How can this be achieved with javascript ?Any examples would be helpful.

You could use local storage or session storage to do that. This is a modern approach that makes use of Web Storage API .

In this case, you may set a property in the storage to hold the button click and only do the refresh if it is not yet clicked.

It is possible to do it like the following snippet:

$('button').on('click', function() {
    // will return null at the first call
    var buttonClicked = sessionStorage.getItem('isButtonClicked');

    // will only enter if the value is null (what is the case in the first call)
    if (!buttonClicked) {
        // set value to prevent further reloads
        sessionStorage.setItem('isButtonClicked', true);

        // reload the page
        window.location.reload();
    }
});

A more detailed example on the web storage API can be found here , if you want to know more details about it.

One way to handle this would be changing the action that onClick performs. Try taking a look here: Change onclick action with a Javascript function

You can try sending a parameter on the first reload and using that parameter change the action of the button.

Something like:

<script>
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return false;
}
var secondReload= getQueryVariable("secondReload");
if(!secondReload){
 //if button clicked
 window.location.reload();
}else{
//deactivate button
}
</script>

you need to add a disabled attribute on the button tag within the click event.

Reloading the page only once on a button click

if you're using jQuery, something like this.

 $('button').on('click',function()({ ... your code here $(this).attr('disabled'); }); 

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