jqueryfor-loop

For LOOP in Jquery: to solve my inefficient code


I was thinking u guys might be able to help.

I now have hundreds of lines of code like the below for each entry. What started as a little stream1 and so on, turned into a mess in my file.

So the code goes from streamtitle1 all the way to streamtitle30 now. The only thing that changes is the

       $("#streamtitleXX").click(function(){
       $("#streamXX").show();
       and all other hide.

This is an example of entry 23. PLEASE HELP WITH AN EFFICIENT "WHATEVER" LOOP. I WILL GIVE YOU A SHOUT OUT ON MY PAGE.

$("#streamtitle23").click(function(){
$("#stream0").hide();
$("#stream23").show();
$("#stream1").hide();
$("#stream2").hide();
$("#stream3").hide();
$("#stream4").hide();
$("#stream5").hide();
$("#stream6").hide();
$("#stream7").hide();
$("#stream8").hide();
$("#stream9").hide();
$("#stream11").hide();
$("#stream10").hide();
$("#stream12").hide();
$("#stream13").hide();
$("#stream14").hide();
$("#stream15").hide();
$("#stream16").hide();
$("#stream17").hide();
$("#stream18").hide();
$("#stream19").hide();
$("#stream20").hide();
$("#stream21").hide();
$("#stream22").hide();
$("#stream23").hide();
$("#stream24").hide();
$("#stream25").hide();
$("#stream26").hide();
$("#stream27").hide();
});

THANKS


Solution

  • DEMO

    $("[id^=streamtitle]").on('click', function () {
        $("[id^=stream]:not([id^=streamtitle])").hide();
        var num = $(this).attr('id').replace('streamtitle','');
        $("#stream"+num).show();
    });
    

    ...but I still say that a common class is the way to go.