Simple JQuery problem

Hi guys, I am writing a simple JQuery function that is supposed to be reusable. It perfoms by allowing buttons on a nav bar to gain an active class when selected. I can get it working but can not when I call a function within a function. If someone could explain to me why this happens I would be very grateful!

     function navButtons (el) {
        $(el).removeClass('active');
        $(this).addClass('active');
    }

    $('.tabLeft').on('click', function() {
        navButtons ('.tabLeft');
    });

I’m not entirely sure about this but try changing $(this) to $(el). I’m not sure what this will be pointing to in this context, so maybe the issue is that you refer an unintended context using it.

If you wan to use a function within a function, try using a closure that has reference to the elements in the DOM so they aren’t lost or can’t be referenced in the child function especially if there are any async operations going on.

In this case $(el) is all the nav buttons, and I need to use $(this) in order to re-add the class back to the clicked button. I’ve been stumped for ages! this works:

 $('.tabLeft').on('click', function() {
    $('.tabLeft').removeClass('active');
    $(this).addClass('active');
});

:frowning:

I’m sorry rledford, I don’t think I’m at the same level as you and am a bit lost with understanding your response! I’ve managed to use closures before and had no troubles at all doing so. Would you know if this line:
$(this).addClass('active');

understands that even though it’s within function navButtons it should refer to the element the user clicked? Or is it now referring to the attribute passed through the function?

I was answering a different question, I misunderstood. I’m glad you got it working. I spotted a similar solution on Stack Overflow.

Ah I was confused about why you were using this instead of el. Glad you got it working! Also I think adding something like:

$('.tabLeft').removeClass('active').bind(this); 

Might have worked?

1 Like