saltcod
saltcod

Reputation: 2041

Javascript menu styling — loop within a loop

A codepen here: http://codepen.io/saltcod/pen/ufiHr

I'm trying to style the menu. I want each item to have a different background opacity—that part is working.

The part that I can't figure out is how to reset the opacity after item #5. When the loop reaches item #6, I want the opacity to go back to what it was in #1.

In case that doesn't make any sense, here's a screen: http://cl.ly/image/0x3e350H0l0o

I basically want to change the opacities five times, then start at the top again.

JS:

var menuItems = $('li a');

menuItems.each(function(index, value){
  var index = index + 1;  
      startOpacity = .2 + index/10;
      counter = .05;
  $(this).css({'background-color': 'rgba(255,255,255,'+startOpacity+')'});
  $(this).append(" " + index);

});

Upvotes: 0

Views: 113

Answers (1)

PSL
PSL

Reputation: 123739

You can take the help of modulus operator to recycle.

menuItems.each(function (index, value) {
    var index = index + 1, 
        startOpacity,
        counter, $this = $(this);

    startOpacity = .2 + (index % 5) / 10; //Here, you can give probably half the number of your menu items instead of 5
    counter = .05;

    $this.css({
        'background-color': 'rgba(255,255,255,' + startOpacity + ')'
    }).append(" " + index);

});

CodePen

Upvotes: 1

Related Questions