Web Analytics Made Easy -
StatCounter jQuery each() infinite loop - CodingForum

Announcement

Collapse
No announcement yet.

jQuery each() infinite loop

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • jQuery each() infinite loop

    Hi there,

    I have this code which I'm trying to use to apply a class name to each list item.

    car $myClass = ["teal", "peach", "salmon", "pink", "blue"];

    $('#Navigation ul li').each(function(index){
    $(this).addClass($myClass[index]);
    })

    The problem is that when it reaches the end of the array it stops. How can I keep looping incase there is more than 5 list items?

    Thanks

  • #2
    this will add a class of indexover to the rest of the li's in question. I am assuming you would like to just start over from the array classes. that will require some type of math calculation in the else block, but frankly i suck at math so i didnt even try.
    Code:
    var $myClass = ["teal", "peach", "salmon", "pink", "blue"];
    var $l = $myClass.length
    
    $('#Navigation ul li').each(function(index){
    if ( index < $l){
     $(this).addClass($myClass[index]);
    }
    else{
    $(this).addClass('indexover');
    }
    })
    - Firebug is a web developers best friend! - Learn it, Love it, use it!
    - Validate your code! - JQ/JS troubleshooting
    - Using jQuery with Other Libraries - Jslint for Jquery/other JS library users

    Comment


    • #3
      Try this. It uses the modulo operator for the loop
      Code:
      var $myClass = ["teal", "peach", "salmon", "pink", "blue"];
      var $l = $myClass.length
      
      $('#Navigation ul li').each(function(index){
       $(this).addClass($myClass[index % $l]);
      })

      Comment


      • #4
        For some reason that if statement seems to break the code. It looks like it makes sense though. Maybe a syntax error?

        Comment

        Working...
        X
        😀
        🥰
        🤢
        😎
        😡
        👍
        👎