Amir Khadem
Amir Khadem

Reputation: 681

Javascript preserving a URL parameter on page change

I'm using Vanilla Javascript,

I have two pages, page01.html and page02.html these pages share the same navigation system.

I want to load a parameter into the url of page01, and after I click page02 on navigation, page02 will load with the parameter within its URL.

example:

  1. I'm on page01.html
  2. I load a param into the URL, so now I have page01.html/?param=X
  3. I click the menu item page02
  4. I want to load page02.html/?param=X

Is there any way to do this without using localStorage and sessionStorage?

Upvotes: 0

Views: 2072

Answers (2)

Amir Khadem
Amir Khadem

Reputation: 681

I used both Bergi's comment and Henry's answer to create my own version.

Basically I just created a onclick="menuClick();" and an id="menuLink" on the a tag. Then on the Javascript I just added the location.search to the href:

menuClick = function() {
    document.getElementById('menuLink').href += location.search
  }

Upvotes: 0

HenryDev
HenryDev

Reputation: 4973

Here's a simple solution using vanilla JavaScript:

Page01.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>

<div>Page 1</div>

<a href="page02.html">go to page 2</a>

<script>
   var linkToPage2 = document.querySelector("a[href='page02.html']");
   linkToPage2.addEventListener("click", function(e){
   e.preventDefault();
     if(location.search){
       window.location.href = "page02.html" + location.search; 
     }
 });

</script>
</body>
</html>

Page02.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>

<div>Page 2</div>

<a href="page01.html">go to page 1</a>

<script>
    var linkToPage1 = document.querySelector("a[href='page01.html']");
    linkToPage1.addEventListener("click", function(e){
     e.preventDefault();
        if(location.search){ 
             window.location.href = "page01.html" + location.search;
         }
     });
 </script>
 </body>
 </html>

Upvotes: 1

Related Questions