Anthony
Anthony

Reputation: 55

Jquery add Class and use as selector?

Hey so I'm really not sure what I'm doing wrong with this,

Basically I have a button 'a#mobile_menu_btn' which I am adding a class to, '.active' which I then want to use as a selector, but it won't work.

 $('a#mobile_menu_btn').click(function () { 
        $('a#mobile_menu_btn').addClass('active');
        $('#mobile_nav').addClass('expand');
    });

 $('a#mobile_menu_btn.active').click(function () { 
         $('#mobile_nav').addClass('expand');
         $('a#mobile_menu_btn').removeClass('active');
        
    });

I am unable to use toggle, as the button performs other functions so I wanted to keep it simple and just use Add / Remove class as when appropriate.

I've tried every variety of writing '$('a#mobile_menu_btn'); including ;

$('a#mobile_menu_btn.active')
$('a#mobile_menu_btn .active')
$('span#mobile_menu_btn.active')
$('div#mobile_menu_btn.active')
$('a#mobile_menu_btn.active')

Where am I going wrong? Thanks in advance

Upvotes: 0

Views: 3670

Answers (1)

Satpal
Satpal

Reputation: 133403

As you are adding class dynamically.

You need to use Event Delegation. You have to use .on() using delegated-events approach.

General Syntax

$(document).on(event, selector, eventHandler);

Ideally you should replace document with closest static container for better performance.

$(document).on('click', 'a#mobile_menu_btn.active', function () { 
     $('#mobile_nav').addClass('expand');
     $('a#mobile_menu_btn').removeClass('active');
});

However You don't need event delegation as you can achieve same thing using .hasClass()

$('a#mobile_menu_btn').click(function () { 
    if($(this).hasClass('active')){
        $(this).removeClass('active');
    }else{
        $(this).addClass('active');
    }
});

Upvotes: 2

Related Questions