Reputation: 317
I have a sidebar, and i am trying to use Javascript to change the appearance as well as destination page on click. However I have tried many suggestions with no luck and I don't understand why.
I've tried using this JS code:
$(document).ready(function () {
var url = window.location;
$('.navigation ul li a[href="'+url+'"]').parent().addClass('active');
});
However, once I've added a href="~/~"
attribute, I get an "Unknown Command: [Link in href]"
- and the "active"
class isn't added to the element.
Thanks for your time
Upvotes: 1
Views: 492
Reputation: 790
Try this,
var url = window.location;
// Will only work if string in href matches with location
$('.navigation ul li a[href="'+ url +'"]').parent().addClass('active');
// Will also work for relative and absolute hrefs
$('.navigation ul li a').filter(function() {
return this.href == url;
}).parent().addClass('active');
Upvotes: 0
Reputation: 6334
For your code you need to set the url to var url = window.location.host+window.location.path';
Upvotes: 0
Reputation: 2397
You're trying to use window.location
to get the current page's URL. However, window.location
is actually an object, that contains multiple properties, and is not a string with the current page's URL. You'll want to use one of the window.location
properties, most likely window.location.pathname
. But, see https://developer.mozilla.org/en-US/docs/Web/API/Location for your complete list of options.
Upvotes: 1