Ravi Chand Dudala
Ravi Chand Dudala

Reputation: 48

How can i Show / Hide Div when i navigate from initial page to another and then come back to initial page?

I have multiple html pages I have some specific content in Home page, its content should not be changed when the page is refreshed or reloaded. But when I navigate to other pages and then come back to Home page, I would like to show / hide div or section of html in the Home page. How this can be achieved?

Upvotes: 1

Views: 82

Answers (3)

azs06
azs06

Reputation: 3517

You can use document.referrer to get the previous page URL and hide the element you want to hide using a condition.

//element to hide
var boxA = document.querySelector('.boxA');
//last page url
var lastPage = document.referrer.split("/").pop();
//checking if element exist and previous page is page B   
if(boxA && lastPage === 'b.html' ){
  boxA.style.display = 'none';
}

StackOverflow snippet doesn't support multiple html pages, please check this plunker to understand the above code better https://plnkr.co/edit/sbBIHf1RZA7YMTL4sJfd?p=preview

Upvotes: 1

yinka
yinka

Reputation: 33

Link from page B to page A with a url querystring. Something like

https://mywebsite.com/a?myParam=1

Then on page A.

var myParam = location.search.split('myParam=')[1]
if(myParam == 1){
document.getElementById('hideDiv').style.display = 'none';
}

Upvotes: 0

Alex
Alex

Reputation: 2780

Add a querystring to the url using JS on page B, then check for it on page A and remove/modify content as needed:

// Set url parameter:

var myURL = document.location;
document.location = myURL + "?a=parameter";


// Check for url parameter:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Upvotes: 0

Related Questions