Reputation: 109
I have a website where I need to have a specific header div display for each of the unique pages within the website (roughly 25 pages). I have created a set of variables and a very long if else statement (simplified below - but runs about 25 if statements deep) to run the function. The function works great except I am having issues with about 8 of the pages not functioning.
The problem: is there a better way to implement this than a run-on if else statement?
Basic code:
<div style="background: url(/image1.jpg)" class="landing hide"></div>
<div style="background: url(/image2.jpg)" class="information hide"></div>
<div style="background: url(/image3.jpg)" class="bell hide"></div>
var landing = "/home";
var information = "/information";
var bell = "/information/bell";
$(function(){
if (location.pathname.search(landing)!=-1){
$('.landing').show();
} else {
if (location.pathname.search(information)!=-1){
$('.information').show();
} else {
if (location.pathname.search(bell)!=-1){
$('.bell').show();
} else {
$('.landing').show();
}
}
}
});
Upvotes: 0
Views: 396
Reputation: 23537
You could create an array of routes
.
var routes = {
"landing": {
"classname": ".landing",
"pathname": /^\/home/
},
"information": {
"classname": ".information",
"pathname": /^\/information/
},
...
};
$(function(){
for(route in routes){
if(routes.hasOwnProperty(route)){
if(window.location.pathname.match(routes[route].pathname) != -1) {
$(routes[route].classname).show();
}
}
}
});
Notice route.pathname
are regular expressions. And the prefix ^
character means that the pathname needs to start with the given string.
Upvotes: 2