Home > Software design >  Click a button when the page reloads
Click a button when the page reloads

Time:04-22

When I click a button (#test-element) it makes the page refresh but I want it to then run a function after the page is refreshed to open the cart by clicking a button automatically(.cart-contents). How do I run a function after the page is refreshed if the add to cart button (#test-element) was clicked. So the page refreshes and clicks another button(.cart-contents)?

<script>
 $("#test-element").on("click",function() {
 setTimeout(function () {
 location.reload(true);
 }, 500);
 });
</script> 
<script type="text/javascript">
  $("#test-element").on("click",function() {
  setTimeout(function () {  
  $(document).ready(function(){
  $(".cart-contents").trigger('click'); 
  }, 500);
  });});
</script>

CodePudding user response:

You can use sessionStorage (only applied to the current session page) to keep your clicking state. After the page is reloaded, we can remove that temporary storage.

You can try this sandbox for the test

$(document).ready(function() {
  $("#test-element").on("click", function() {
    setTimeout(function() {
      sessionStorage.setItem('isReloaded', 'true');
      location.reload(true);
    }, 500);
  });
  $(".cart-contents").on("click", function() {
    alert('cart-content triggered')
  })
  const isReloaded = sessionStorage.getItem('isReloaded');
  if (isReloaded) {
    sessionStorage.removeItem('isReloaded')
    $(".cart-contents").trigger('click');
  }
});

This way is not perfect but it can solve your basic needs in terms of keeping page states.

CodePudding user response:

You probably don't need (or even want) to actually do this. It sounds like an over-complicated solution to a problem of mixing AJAX and page loads/requests, and the real solution would be to fix whatever design problem is causing you to want to do this to compensate for it.

Having said that...

Each time the page loads, the JavaScript starts anew. So any information you want to persist between page loads needs to exist outside of the page code itself. One such place to persist data could be localStorage.

So your operation to reload the page would write a value to localStorage:

$("#test-element").on("click",function() {
  setTimeout(function () {
    localStorage.setItem("clickCartContents", true);
    location.reload(true);
  }, 500);
});

And when loading the page you can check to see if that value was set:

$(document).ready(function(){
  if(localStorage.getItem("clickCartContents")) {
    $(".cart-contents").trigger('click');
    localStorage.removeItem("clickCartContents");
  }
});
  • Related