2

I'm trying to make a javascript code smaller using a for loop, im new to javascript but I thought this would work,

Im trying to make this smaller:

   $("li#li_item1").click(function(){
    all();
    $("div#item1").fadeIn("fast");
})

$("li#li_item2").click(function(){
    all();
    $("div#item2").fadeIn("fast");
})

$("li#li_item3").click(function(){
    all();
    $("div#item3").fadeIn("fast");
})

$("li#li_item4").click(function(){
    all();
    $("div#item4").fadeIn("fast");
})

Using this:

    var AantalItem = 159;

    for(var k=0;k<=AantalItems;k++) {
    $("li#li_item" + k).click(function(){
        all();
        $("div#item" + k).fadeIn("fast");
    })

    document.getElementById("test").innerHTML=k;
}

When using the smaller code the fade in just wont work

This is the all():

    var all = function(){
    for(var i=0;i<=AantalItems;i++) {
        $("div#item" + i).fadeOut("fast");
    }
};

3 Answers3

2

It is due to closures effect.

try this:

for(var k=0;k<=AantalItems;k++) {
  $("li#li_item" + k).click(createClickFunction(k));
}

function createClickFunction(k) {
     return function() {
            all();
            $("div#item" + k).fadeIn("fast");
        }
}
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

you can create a function returning a function and pass k to it:

for(var k=0;k<=AantalItems;k++) {
    $("li#li_item" + k).click((function(k){
        return function() {
            all();
            $("div#item" + k).fadeIn("fast");
        }
    })(k));

or just add a common class to those items, and linked object's id to its data property - then the whole code will look like:

$('.commonClass').click(function() {
    $('.anotherCommonClassForDivs').fadeOut("fast");
    $('div#' + $(this).data('id')).fadeIn("fast");
});

and html:

<li class="commonClass" data-id="item1">whatever</li>
<li class="commonClass" data-id="item2">whatever</li>

<div class="anotherCommonClassForDivs" id="item1">data for item1</div>
<div class="anotherCommonClassForDivs" id="item2">data for item2</div>

LIVE DEMO

Adassko
  • 5,201
  • 20
  • 37
0

Try this..

  function fadeinAll() {
         $('li#li_item').find('div').each(function () { $(this).fadeIn("fast"); })
     }
     function fadeoutAll() {
         $('li#li_item').find('div').each(function () { $(this).fadeOut("fast"); })
     }
Sunny
  • 219
  • 1
  • 10