Dennis Hunink
Dennis Hunink

Reputation: 583

jQuery selector only works on forward elements

I've written some small code that provides a pretty basic functionality and it uses the default jQuery selection methods. It works like this: There are 2 li's which wrap a link. When the link is clicked, jQuery cheks if the li has a certain css class; if not, it performs the required action.

Frankly it works only when the second li doesn't have this class, not when the first hasn't.

Can anyone tell why this happens and how it could be solved?

jsfillde is here and makes things much clearer: http://jsfiddle.net/EDa7n/

Upvotes: 2

Views: 118

Answers (2)

Jim Schubert
Jim Schubert

Reputation: 20357

You're only binding the click function to anchor tags which aren't active.

You need to bind to them all and within the click function, check if the class is active.

http://jsfiddle.net/jimschubert/EDa7n/1/

$(".ui-tabs-nav li a").click(function(){ //Weird, it works only for the second li, not for the first (eg when the second is active)
    $('#BT-tabVerbetering, #BT-tabWens').show();
    if(!$(this).hasClass("ui-state-active")) 
        $('#BT-nieuw').hide();
});

Upvotes: 3

Kevin B
Kevin B

Reputation: 95023

Events are bound to elements at the time that the event binding method is called. Changing the element's class will not change what events are bound to the element. For example, this click event:

$("#BT-menu li:not(.ui-state-active) a").click(function(){...

the li:not(.ui-state-active) a binds the event to the second tab, not the first. The first tab will never have this event bound and the second one will always have the event bound. Instead, you should bind the event to both elements with

$("#BT-menu li a").click(function(){...

and then detect whether or not it is active within the event.


Unreleated, but you really should be posting relevant code and markup in your question rather than simply linking to a jsfiddle. The fiddle is a good addition to the question, however it isn't a replacement for actually posting code.

Upvotes: 2

Related Questions