Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Juan Garcia
10,577 PointsIs there another way to write this JavaScript code?
Can you guys look at my code and see if there's another way to write it. I find it a little repetitive. Here's the link: http://codepen.io/-J0hn-/pen/RoQNeq?editors=0010
1 Answer
Micah Murray
6,913 PointsThe simplest way to reduce this code is to use a for loop as demonstrated below.
// WHEN HOVER THE TRACK NUMBER CHANGES TO A PLAY BUTTON for(i=0; i<12; i++){ $('.inline').eq(i).hover(function() { $('.inline span').eq(i).html('<span class=\'fa fa-play\' style="color:rgb(255,255,255);cursor:pointer;margin-right:-5px;padding-right:0;"></span>'); }, function() { $('.inline span').eq(i).html(i.toString()).css({ 'color': 'rgb(130,130,130)' }); } ); }
// WHEN CLICKED, PLAY BUTTON CHANGES TO PAUSE BUTTON for(i=1; i<13; i++){ $('li span').click(function() { if ($('li span').eq(i).hasClass('fa-play')) { $('li span').eq(i).removeClass('fa-play').addClass('fa-pause'); } else if ($('li span').eq(i).hasClass('fa-pause')) { $('li span').eq(i).removeClass('fa-pause').addClass('fa-play'); } }); }