Nicolas
Nicolas

Reputation: 59

Display div after page reload

I would like to reload my page with javascript and then display a div.

The problem is that with the following code the div is displayed first and then the page reloads:

Part of my fetch function:

.then(result => {
  window.location.reload()
  document.querySelector('#cambiosguardados').style.display = 'block'
})

Is there any way to achieve this? The div is a success message I would like to display but I can't find a way to make this work.

Upvotes: 0

Views: 883

Answers (3)

video-reviews.net
video-reviews.net

Reputation: 2926

Easy Solution

You need a way to store the state as when the page reloads the state will reset.

You can try this

.then(result => {
  window.localStorage.setItem('show_div', 'true');
  window.location.reload();
})

and then some where else on your page

if(window.localStorage.getItem('show_div') == 'true') {
  document.querySelector('#cambiosguardados').style.display = 'block';
} else {
  document.querySelector('#cambiosguardados').style.display = 'none';
}

and then if you ever need to reset it you can use

window.localStorage.removeItem('show_div');

Upvotes: 1

Herman Andres Figueroa
Herman Andres Figueroa

Reputation: 523

When the page is refreshed the entire DOM is re-initialized for this reason this is not possible by refreshing the url, what you can do is send a flag and identify that value like this

OPTION 1: Reload and show message

.then(result => {
    var sucessUrl = new URL(location.href);
    sucessUrl.searchParams.set('success', 1);
    window.location.href = sucessUrl;
})
document.addEventListener("DOMContentLoaded", function(event) {
   const urlParams = new URLSearchParams(window.location.search);
   const success = urlParams.get('success');
   if(success == 1'){
     document.querySelector('#cambiosguardados').style.display = 'block'
   } 
});

OPTION 2: Show message and reload

  document.querySelector('#cambiosguardados').style.display = 'block'
  setTimeout(function () { // wait 1 seconds and reload
     window.location.reload();
  }, 1000);

Upvotes: 0

Joe
Joe

Reputation: 948

The thing is, when the page reloads the JavaScript is going to run again.

Why do you need to reload the page? Why can't you just display the div, what does the reload matter?

You could use search paramaters. So say you window.location.href = "/?success=true"

Then just in the script file at the top you can have a function that calls on load

(function popUp() {
    let params = (new URL(document.location)).searchParams
    let isSuccess = params.get("success")

    isSuccess && document.querySelector('#cambiosguardados').style.display = "block"
})()

Upvotes: 0

Related Questions