Reputation: 23
I have a page (...contacts.asp) with 4 buttons.
When a button is clicked it opens its associated div
section and collapses the other 3 sections. The logic for this works fine.
Now I want to link to this page from another one, but have the associated div
section opened as directed by the #tag
hash in the url link http....contacts.asp#Sales.
My code is as follows, I added the if
statement hoping that would work but it does not.
function showhide(id) {
document.getElementById('Corporate').style.display = "none";
document.getElementById('Outlets').style.display = "none";
document.getElementById('Sales').style.display = "none";
document.getElementById('Service').style.display = "none";
var e = document.getElementById(id);
e.style.display = (e.style.display == 'block') ? 'none' : 'block';
}
if ( location.hash != 0 && location.hash == '#Sales' ){
document.getElementById('Sales').style.display = "block";
}
Upvotes: 2
Views: 142
Reputation: 68
The relevant code probably is executed to early.
More precisely when this code:
if ( location.hash != 0 && location.hash == '#Sales' ) {
document.getElementById('Sales').style.display = "block";
}
is executed, the '#Sales' DOM-Element maybe doesn't exist yet, because the DOM hasn't been loaded completely. So nothing will happen by executing this.
This means the code has to be executed after the DOM is loaded. To do this there is e.g. an 'DOMContentLoaded' event. (You could also use the 'onload' event.)
So as solution you should write the code inside that event handler:
document.addEventListener("DOMContentLoaded", function() {
// the if statement
});
Upvotes: 2