0
var topOptions = ["#m1", "#m2", "#m3", "#m4", "#m5", "#m6"];
for(i = 0; i < topOptions.length - 1; i++)
{

    $(topOptions[i]).click(function(){
        $(topOptions[i]).animate({backgroundColor: '#2c3e50'}, 150);
      });
}

I'm trying to have something happen upon clicking each element, however only the last one is triggered. How do I do this?

tommyzat
  • 3
  • 5

4 Answers4

0

Try this:

var topOptions = ["#m1", "#m2", "#m3", "#m4", "#m5", "#m6"];
$.each(topOptions,function(i,item){
$(item).animate({backgroundColor: '#2c3e50'}, 150);
});
Ashiquzzaman
  • 5,129
  • 3
  • 27
  • 38
0
$(this).animate .... 

instead of

$(topOptions[i]).animate ....
Furkan
  • 415
  • 5
  • 17
0
 $("a").click(function(){
 var topOptions = ["#m1", "#m2", "#m3", "#m4", "#m5", "#m6"];
 if(jQuery.inArray( $(this).attr("id"),topOptions )>-1){
 $(this).animate({backgroundColor: '#2c3e50'}, 150);
 }
 });

note that I use a as a selector if it is a div or something else change this

$("a)

I think you want this function jQuery.inArray which check if your clicked id found in topOtions array

Osama
  • 2,912
  • 1
  • 12
  • 15
0

Note, you can't animate backgroudColor using jQuery animate. You could use css tansition to animate background color. Here is a solution you could use

var ids = ['#id1','#id2','#id3','#id4','#id5'];

ids.forEach(function(id){
 $(id).click(function(e){
  $(this).css('backgroundColor', '#2c3e50')
 });
});
li{
 -webkit-transition: background 0.5s linear;
-moz-transition: background 0.5s linear;
-ms-transition: background 0.5s linear;
-o-transition: background 0.5s linear;
transition: background 0.5s linear;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JavaScript</title>
</head>
<body>
<ul>
 <li id="id1">id1</li>
 <li id="id2">id2</li>
 <li id="id3">id3</li>
 <li id="id4">id4</li>
 <li id="id5">id5</li> 
 </ul> 
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

</body>
</html>

To know about why your for loop working for last element, please check this answer JavaScript closure inside loops – simple practical example

Community
  • 1
  • 1
azs06
  • 3,467
  • 2
  • 21
  • 26