How Do I go back to my html page without losing the index of it?

Advertisements

I have two html page. From Page 1 I can go to page 2 and from page 2 I can go back to Page 1.

In page 1 I have a button that display an Image. When I go to page 2 and back to page 1 my image disappear. Is there a way to not lose what I did on page 1 when I go back to it?

<html>

<head>
    <title>
        Onclick javascript to make browser go
        back to previous page?
    </title>
</head>

<body>
<button onClick="showImage()">Button</button>
<div id="first" style="height:200px; width:200px; display:none;">
    <img src="PP.jpg"/>
</div>

<script>
    const showImage = () => {
        document.getElementById("first").style.display ='block';
    }
</script>

    <h1 style="color: green">
        GeeksforGeeks
    </h1>

    <b>
        Onclick javascript to make browser
        go back to previous page?
    </b>

    <h2>Page 1</h2>

    <p>
        Click on the link to get
        to the second page.
    </p>

    <a href="Page2.html">Go to Page 2</a>
</body>

</html>

I am currently using onclick="history.back()" for it refresh my starting page and remove the image

<!DOCTYPE html>
<html>

<head>
    <title>
        Onclick javascript to make browser
        go back to previous page?
    </title>
</head>

<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>

    <b>
        Onclick javascript to make browser
        go back to previous page?
    </b>

    <h2>Page 2</h2>

    <p>
        Click on the button to go
        back to the previous page.
    </p>

    <button onclick="history.back()">
        Click here to go back
    </button>
</body>

</html>

>Solution :

You need to save the state in a storage, for example a sessionStorage.
You can handle it with the onload Event.

You need to save the state in the storage when the button is clicked to show the image. And when the page reloads, check if the button is clicked, if so then show the container else don’t show.

const showImage = () => {
 sessionStorage.setItem('showImage', 'true');
 document.getElementById("first").style.display ='block';
}
    
function myFunction() {
  if (sessionStorage.getItem('showImage') === 'true') {
   document.getElementById("first").style.display ='block';
   sessionStorage.removeItem('showImage');
  }
}

on the body tag add this:

<body onload="myFunction()">

For example:
https://jsfiddle.net/dn09ysa1/

Leave a ReplyCancel reply