Xtian
Xtian

Reputation: 3587

Hide or Show if Current, jQuery

I have this list:

<ul class="pagination">
    <li class="dl-nav-1 current"><a href="#">Spring Training 2001</a><span class="visible"><img src="img/indicator.png" alt="" /></li>
    <li class="dl-nav-2"><a href="#">NFL 2011</a><span class="hidden"><img src="img/indicator.png" alt="" /></span></li>
    <li class="dl-nav-3"><a href="#">Fantasy Baseball</a><span class="hidden"><img src="img/indicator.png" alt="" /></span></li>
</ul>

I need to show the <span> when the li class is current, and hide the <span> when it is not current.

There is a JS plugin that will change the li class, so when it changes to current, make <span> visible and when it removes current, hide <span>

terrible attempt:

$(function) () {
    if($(ul.pagination li).hasClass("current")) {
        $("ul.pagination li.current span").removeClass("visible").addClass("hidden");
    } 
    else{
        $("ul.pagination li.current span").removeClass("hidden").addClass("visible")
    }

};

Upvotes: 0

Views: 1036

Answers (4)

Ryley
Ryley

Reputation: 21226

You only need javascript to do the toggling of classes, CSS can do the rest:

ul.pagination li.current span {
    display:inline;
}

ul.pagination li span {
    display:none;   
}

Then, using Justin808's example, you'd do something like this for the javascript:

function ToggleIndicator(liClass) {
    $('.'+liClass).toggleClass('current');
}

$('#clickme').click(function() { ToggleIndicator('dl-nav-3');}); 

Forking Justin808's jsfiddle, you get this: http://jsfiddle.net/uwTEZ/1/

Upvotes: 2

Kon
Kon

Reputation: 27451

With jQuery you can easily add/remove this class from element like so:

$('.dl-nav-1').find('span').addClass('visible');
$('.dl-nav-2').find('span').removeClass('visible').addClass('hidden');

Easier way to reset all list items, before setting one to current:

$('.pagination').children().find('span').removeClass('visible').addClass('hidden');

Upvotes: 0

Justin808
Justin808

Reputation: 21522

Here is an example that will hide and show based on your classes. Any time you change your classes, call the 'UpdateIndicators' function.

Update:

If you want to update the indicators via javascript, here is an example with a toggle function.

Upvotes: 0

Related Questions