Search code examples
javascriptjquerycycle

problem with cycle for


I have a cycle that it's just working for my last element. It was suposed to work for each element.

for (var z=1; z<$('.page').length;z++){ 

$('#arrowUp_'+z).click(function(){
        $('#thumbsContainer_'+z).animate({top: '-='+93+'px'}, {duration: 1000});
        cont++;
        arrowThumbs();
    });

    $('#arrowDown_'+z).click(function(){
        $('#thumbsContainer_'+z).animate({top: '+='+93+'px'}, {duration: 1000});
        cont--;
        arrowThumbs();
    });
}

If I replace z for one number I can make it working for that case. But I don´t want to repeat the same process N time. So I thought it was good idea to make a a cycle for...but no success

Can anyone explain how to do that?? Thanks


Solution

  • Why are you using IDs? why can't you just add a class on each element like so

    <div id="arrowUp_1" class="arrowUp">
    
    </div>
    

    $('.arrowUp').click(function(){...});

    also [things you should know]

    '-='+93+'px' its pointless you can have '-=93px' still be the same thing as it would be consider as a string not a number its just like saying var h3ll0; is not a string :)

    cont++ is not predefined before and your whole don't work because animate() is wrong... click the link so u can get some help with it http://api.jquery.com/animate/

    you do not put {duration:1000} just put 1000 as that is an attribute on its own and expects a number [of milliseconds not a json object]...

    UPDATE check this code...

    http://jsfiddle.net/JFRAb/3/

    ==============================================

    CSS:

    span {background: red;position: absolute; left: 0;}

    JS

    $(function() {
        $('div').click(function() {
            $('p').append($(this).text());
            //alert('text');
            var i = $(this).index($('ul div'));
            console.log($(this));
            $('ul span').eq(i).animate({
                left: '50%'
            }, 1000);
        });
    });
    

    HTML

    <p>Test...</p>
    <hr />
    <ul>
        <div>Click 1</div>
        <div>Click 2</div>
        <div id="b">Click 3</div>
        <div>Click 4</div>
    </ul>
    <br /><br /><br /><br />
    <ul>
        <span>Im thumb 1</span>
        <span>Im thumb 2</span>
        <span>Im thumb 3</span>
        <span>Im thumb 4</span>
    </ul>
    

    This is a bad example of element choice :) but its better solution for you :) I should think :)