0

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.

themaster
  • 453
  • 11
  • 32

4 Answers4

1

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.

Bruno Toffolo
  • 1,504
  • 19
  • 24
0

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

Community
  • 1
  • 1
Simon
  • 855
  • 9
  • 24
0

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>
Agu V
  • 2,091
  • 4
  • 25
  • 40
-2

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');
});
Community
  • 1
  • 1
Mark Handy
  • 1,180
  • 1
  • 11
  • 23
  • It is possible to do that without disabling the button. – Bruno Toffolo Jun 28 '16 at 18:55
  • i read the OP as he wanted to avoid people double clicking the button while the reloaded happen. So diasable it. Or remove it from DOM. – Mark Handy Jun 28 '16 at 18:57
  • 1
    He explicitly mentioned that "from the second click and till the HTML page is active the reload should not be called" -- so the button can still be clicked, but nothing should happen. – Bruno Toffolo Jun 28 '16 at 19:03