Search code examples
jqueryloopsfor-loopattr

appyling a function for all relevant tags - jquery


I'm figuring jQuery out at the moment. there are 6 <li> tags with custom attr called data-index="x" (x is just numbers 0 to 6).Basically I'm trying to apply for loop rather than writing it over and over yet I've failed so far.

here is the code:

for (var i=0; i<6; i++) {
    var m = 'i*-40' + 'px'
    $('li[data-index="i"] p')
    .css( {backgroundPosition: "-150px m"} )
    .mouseover(function(){
        $(this).stop().animate({backgroundPosition:"(0 m)"}, {duration:300})
    })
    .mouseout(function(){
        $(this).stop().animate({backgroundPosition:"(-150px m)"}, {duration:300})
    });
}

Solution

  • Variables inside strings aren't magically evaluated.

    You should use something like

    for (var i=0; i<6; i++) {
        var m = i*-40 + 'px';
        $('li[data-index="' + i + '"] p')
        .css( {backgroundPosition: "-150px " + m} )
        .on('mouseover', function(){
            $(this).stop().animate({backgroundPosition:"0 " + m}, 300)
        })
        .on('mouseout', function(){
            $(this).stop().animate({backgroundPosition:"-150px " + m}, 300)
        });
    }