Reputation: 91
I have a static HTML sidebar which seems to be added every time I load the page on my website by the custom sidebar plugin I use (WordPress).
I'm trying to add a class to the current active A tag on the sidebar so I can style it.
Since it's adding the static HTML sidebar every time I load the page, the class that I'm adding is deleted after the next page loads.
Is it a way to add the class after the next page loads? Or maybe preserve the element in question in a variable until the next page is loaded?
$(document).ready(function() {
var selector = 'a.custom-sidebar-item';
var url = window.location.href;
$(selector).each(function(){
$(selector).removeClass('active-custom-sidebar-item');
if(url == $(this).attr('href')) {
$(this).addClass('active-custom-sidebar-item');
$(this).css("border-bottom", "2px solid red");
}
});
});
EDIT:
Changed the code a bit.
Here is what I'm having in the console log - https://i.sstatic.net/YGtHU.jpg.
And here is what I'm trying to achieve - https://i.sstatic.net/3JjCN.jpg.
Workaround What actually worked was "$(this).css("border-bottom", "2px solid red");". Still not sure why "$(this).addClass('active-custom-sidebar-item');" is not working. So I add the css directly with jQuery, instead of adding the class on load. Which I guess is better after all.
P.S.: The reason why I don't use .siblings() to remove the class from the other sidebar links is that some of them are tags in an and some are tags. Will optimize the code later. The code currently adds the class (checked with console.log) but when the next page loads it gets overwritten.
Upvotes: 0
Views: 42
Reputation: 916
Place the same script on all the pages. You can do this by including it on common footer of wordpress. In your code, you are probably removing the class immediately after adding it, try this.
$(document).ready(function() {
var selector = 'a.custom-sidebar-item';
var url = window.location.href;
$(selector).removeClass('active-custom-sidebar-item');
$(selector).each(function(){
if(url == $(this).attr('href')) {
$(this).addClass('active-custom-sidebar-item');
}
});
});
Upvotes: 0
Reputation: 91
The solution for me happened to be... Instead of:
$(this).addClass("active-custom-sidebar-item");
to actually:
$(this).css("border-bottom", "2px solid red");
on window.ready() after checking the element with the URL we are on. Adding the style with the script worked, so anyway I achieved the desired result, but still not sure why adding the class didn't work...
Upvotes: 0