S.P.
S.P.

Reputation: 369

jQuery - Add class based on url and without url

[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!

Upvotes: 1

Views: 73

Answers (2)

Anand G
Anand G

Reputation: 3200

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/

Upvotes: 0

Vishal Kiri
Vishal Kiri

Reputation: 1306

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.

Upvotes: 1

Related Questions