1

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.

4
  • Yes, there would be two // before mysite Commented Oct 26, 2018 at 1:50
  • Use a string replacement to replace your scheme://domain.tld/ with "" then you will only have your resource path left. Commented Oct 26, 2018 at 1:52
  • Ignore this fact that i'm using '/' or '//' it isn't the issue root. The SO blocked my post when I wrote '//' in the domain Commented Oct 26, 2018 at 1:54
  • It was blocking the mysite.com part of it, just change to example.com and it will be accepted (hope that's OK) Commented Oct 26, 2018 at 2:01

2 Answers 2

2

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' 
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.