javascripthtmlcsssession-storage

Make the hidden image appear after pressing the browser refresh, with just one click


With this code below, I hide the image after pressing the button click. When I navigate between other pages, the image should remain hidden. This is working fine. When the user clicks on browser refresh, the image should appear again. The problem is that the image is only appearing after the user clicks twice on refresh. I would like it to appear after a single click. Below is a summary for clarity.


Solution

  • updated and checked it should work now:

    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    
      <style>
        .btn-close {
          width: 166px;
          height: 44px;
          margin-top: 12px;
          font-size: 25px;
        }
      </style>
    </head>
    
    <body>
    
      <div class="img-container">
        <img class="img" src="https://images.pexels.com/photos/163236/luxury-yacht-boat-speed-water-163236.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1&cache_bust=<%= new Date().getTime() %>" alt="">
        <button class="btn-close">Fechar</button>
      </div>
    
      <script>
        (function () {
          const image = document.querySelector('.img');
          const btnClose = document.querySelector('.btn-close');
          let visibility = sessionStorage.getItem('visibility');
    
          if (performance.navigation.type === 1) {
            let currentTime = new Date().getTime();
            let lastLoadedTime = sessionStorage.getItem('lastLoadedTime');
            if (lastLoadedTime && (currentTime - lastLoadedTime) < 1000) {
              visibility = sessionStorage.getItem('visibility');
              image.style.display = visibility === 'visible' ? 'block' : 'none';
            } else {
              sessionStorage.setItem('visibility', 'visible');
              visibility = 'visible';
              image.style.display = 'block';
            }
            sessionStorage.setItem('lastLoadedTime', currentTime);
          }
    
          btnClose.addEventListener('click', () => {
            image.style.display = 'none';
            sessionStorage.setItem('visibility', 'invisible');
          });
    
          if (visibility === 'invisible') {
            image.style.display = 'none';
          } else {
            image.style.display = 'block';
          }
        })();
      </script>
    </body>
    
    </html>
    

    I hope it helps