I have am trying to create jQuery code which adds a active-menu class to a link whenever I click on it. However I need to check first if it already has the class before adding. I only need the link that was clicked to get the class.
<%= link_to "Testimonials", root_path, class: "nav-link js-nav", :"data-id" => "testimonials" %>
$(document).on('click', function() {
var item = $('.js-nav');
if (item.hasClass('active-menu')) {
item.removeClass('active-menu');
}
item.addClass('active-menu');
});
I thought this would work but as of now it puts active-menu on all the items that has js-nav. Again, I only need to add the class if it doesn't have it yet and only need to add on the click item.
'.js-nav'instead of the whole document and add the class tothisinstead of all instances of'.js-nav'.$(document).on=$('.js-nav').on..var item = $('.js-nav');=var item = $(this);– Lain 2 days ago