2

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.

  • Put the click event on '.js-nav' instead of the whole document and add the class to this instead of all instances of '.js-nav'. $(document).on = $('.js-nav').on.. var item = $('.js-nav'); = var item = $(this); – Lain 2 days ago
  • I don't understand the purpose of .js-nav. If item = js-nav then, that's exactly what you are doing. If it does not have it, add it, means, all of the items should have it added, so basically, you can do if it does not have it, add it, instead – Iria 2 days ago
5

A more simplified solution:

        $(document).on('click', '.js-nav', function() {
            $(this).toggleClass("active-menu");
        });

Refer: https://api.jquery.com/toggleclass/

  • For some it's removing the class. – James Hedegon 2 days ago
  • @JamesHedegon you can modify the function to add a class after adding a check – K K 2 days ago
1

Try this

$(document).ready(function () {
    $(this).on('click', '.js-nav', function() {//  here $(this) is refering to document
        $(this).addClass('active-menu');
    });
});
0

Set the class on $(this) instead of every element that matches class

Also, add class in the else conditions, otherwise it will add class even after removing it

Like this

$(document).on('click', function(){
    var item = $(this);
    if (item.hasClass('active-menu')){
      item.removeClass('active-menu');
    } else{
      item.addClass('active-menu');
    }
});
0

you need to use $(this) to get the currently clicked link and then check hasClass. Also, in if condition you are removing it and again adding it, instead you can check if no class present then add it otherwise don't do anything.

Also, add click event handler for .js-nav instead of all document

$(document).on('click', '.js-nav', function(){
    if (!$(this).hasClass('active-menu')) {
        $(this).addClass('active-menu');
    } 
});
  • The if statement is redundant – Rory McCrossan 2 days ago
  • did not understand why it is redundant as i am adding class only if it is not there. Can you please elaborate more – Bhushan Kawadkar 2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.