1

[Update code again] I have the following code:

var header_url = window.location.href;
if(/index/.test(header_url)||/home/.test(header_url)){
    $('#home').addClass('select');
} else if(/about/.test(header_url)) {
    $('#about').addClass('select');
} else if(/contact/.test(header_url)) {
    $('#contact').addClass('select');
}

The code is work, when I click them:

http://example.com/index.html
http://example.com/about.html
http://example.com/contact.html

But if I want to add another page, set it as default main page without url, like this:

http://example.com

I try to add code but it doesn't work:

else if(/.test(header_url)) {
        $('#default').addClass('select');
    }     

Can anybody help please? thx!

5
  • 1
    Use default case in switch Commented Sep 4, 2015 at 6:44
  • @Tushar Sorry I posted the wrong code, can you please check again? Commented Sep 4, 2015 at 7:08
  • Then add an else at the end and use it for default case Commented Sep 4, 2015 at 7:09
  • yes, you will use else on behalf default. Commented Sep 4, 2015 at 7:12
  • fixed it, big thx for your help!!!! Commented Sep 7, 2015 at 3:58

2 Answers 2

1

you have used default in switch case like

switch (window.location.pathname) {
case '/index':
$('#home').addClass('select');
break;
case '/about':
$('#about').addClass('select');
break;
case '/contact':
$('#contact').addClass('select');
break;
default:
 $('#default').addClass('select');
break;
}   

try this.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry I posted the wrong code, can you please check again? thx!
0

You have not created proper expression for last condition. Try below code

var header_url = 'http://example.com';
//var header_url = 'http://example.com/index.html';
//var header_url = 'http://example.com/about.html';
//var header_url =  'http://example.com/contact.html';
if(/index/.test(header_url)||/home/.test(header_url)){
    console.log('index');
} else if(/about/.test(header_url)) {
    console.log('about');
} else if(/contact/.test(header_url)) {
    console.log('contact');
} else if(/\//.test(header_url)) {
   console.log('nothing');
}   

Check this fiddle too http://jsfiddle.net/anandgh/k63f3a33/1/

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.