Reputation: 1090
I have solve a solution that make conditional to know if I'm NOT in the index page, the background image of an element should be none. How can I do this without need to write the page domain? A solution better than this:
if(window.location.href != 'http://example.com/'){
document.querySelector('.menu-principal')
.style.backgroundImage = 'none'
}
I'm only want to know if I'm in the index page or Not, without need to write the page domain.
Upvotes: 1
Views: 479
Reputation: 370709
One option is to check location.pathname
, which will hold everything in the URL string past the domain - for example, for this page, whose URL is
https://stackoverflow.com/questions/53000339/javascript-conditional-using-the-domain-name/53000364
the pathname is
/questions/53000339/javascript-conditional-using-the-domain-name/53000364
When on an index page, even when there's no trailing /
in the URL string, the pathname is /
. So, if your pathname is anything other than /
, you know that you're on somewhere other than the index page:
if (window.location.pathname !== '/'){
document.querySelector('.menu-principal')
.style.backgroundImage = 'none'
}
Upvotes: 2
Reputation: 44107
Use this:
var { pathname } = window.location;
if (!(pathname == "" || pathname == "/" || pathname == "/index.html")) {
document.querySelector(".menu-principal").style.backgroundImage = "none";
}
So the following would all be the index page, and therefore the background image would be visible:
https://stackoverflow.com
https://stackoverflow.com/
https://stackoverflow.com/index.html
Upvotes: 0