Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Short-Hand Code For a Long List of Same Function

Tags:

jquery

I have an HTML structure like this below:

List
<ol id="years">
<li class="2011">2011</li>
<li class="2012">2012></li>
<li class="2013">2013></li>
</ol>

News:
<div class="news 2011">Some News here</div>
<div class="news 2012">Some News here</div>
<div class="news 2013">Some News here</div>

I am in need of a short-hand code of the code below(It works, but i want it to be automated, not manual):

$('.2011').click(function() {    
    $(".news").show().not('.2011').hide()
 return false;
        });

$('.2012').click(function() {    
    $(".news").show().not('.2012').hide()
 return false;
        });

$('.2013').click(function() {    
    $(".news").show().not('.2013').hide()
 return false;
        });

What i tried was:

for(i=2011; i<= 2020; i++){

$('.'+i+'').click(function() {    
    $(".news").show().not('.'+i+'').hide();
 return false;
        });
}

When i click on a li item, it just hides everything, so it is not the expected result.

Any help is appreciated. Thanks for your time!

like image 223
Tumay Avatar asked Jan 29 '26 15:01

Tumay


1 Answers

$('#years li').click(function(){
    $('.news').show().not('.' + $(this).attr('class')).hide();
    return false;
});

A better way is probably storing the year in a data attribute, eg:

<ol id="years">
    <li class="2011" data-year="2011">2011</li>
    <li class="2012" data-year="2012">2012></li>
    <li class="2013" data-year="2013">2013></li>
</ol>

Then going:

$('#years li').click(function(){
    $('.news').show().not('.' + $(this).data('year')).hide();
    return false;
});

Then you avoid issues if you add other classes to the li items.

like image 100
temporalslide Avatar answered Feb 01 '26 09:02

temporalslide



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!