Sebsemillia
Sebsemillia

Reputation: 9476

how to make jquery react when class changes

I have a simple Tab Navigation with jquery. Whenever a new tab is clicked, the script adds to the current navigation list element the class "currentNav" and deletes it from the previous selected list element. Now I want to change the background of the mother ul whenever the second list element gets the class "currentNav". The start default is that the first list element has this class. My problem is, I don't know how I can make jquery react on that change..

Here is the html of the navigation

<ul id="AuktionenNav">
                    <li><a class="tabSelect one currentNav" href="#Tab0" rel="0">Auktionen starten</a></li>
                    <li><a class="tabSelect two" href="#Tab1" rel="1">Eingestellte Auktionen</a></li>
                </ul>

And here my jquery so far

if($("ul#AuktionenNav li a.two").hasClass("currentNav")) {
        $("ul#AuktionenNav").css("background-image", "url(../system/css/images/eingestellte_Auktionen.png)")
    }

I appreciate any help! Thx!

Upvotes: 1

Views: 1461

Answers (3)

SeanCannon
SeanCannon

Reputation: 77956

Set a trigger and a bind:

// When an <li> (NOT the first one) is clicked, tell the <ul>
$('ul#AuktionenNav li').not(':first-child').click(function(){ 
    $(this).trigger('li_clicked'); 
});

// When the FIRST <li> is clicked, reset the background
$('ul#AuktionenNav li:first-child').click(function(){ 
    $('ul#AuktionenNav').css("background-image", "url(../system/css/images/default.png)");
});
// Listen for an <li> click
$('ul#AuktionenNav').bind('li_clicked',function(){
    $(this).css("background-image", "url(../system/css/images/eingestellte_Auktionen.png)");
});

I know your example only has two <li> tags, but this will scale easily while keeping the first <li> the "resetter"

Upvotes: 3

David Thomas
David Thomas

Reputation: 253308

One way of doing this is to use the DOM mutation events:

$('ul').bind('DOMSubtreeModified',

function() {
    $(this).closest('ul').addClass('red');
});

$('#toggle').click(
    function(){
        $('ul li:nth-child(2)').toggleClass('highlight');
        return false;
    });

JS Fiddle demo.

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206048

HERE IS A DEMO

$('ul#AuktionenNav li a').click(function() {
    $(this).addClass('currentNav');
    if ($("ul#AuktionenNav li a.two").hasClass("currentNav")) {
        $("ul#AuktionenNav").css("background-image", "url(../system/css/images/eingestellte_Auktionen.png")
    }
});

Upvotes: 0

Related Questions