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

JavaScript

Dave Six
Dave Six
8,366 Points

Dynamic colors for divs

I'm writing a Web App for some practice and I'm about to add some colors to some circles. Depending on the genre, I'd like to change the color.

My HTML for each song looks like this:

<div id="song">
  <p class="title">Title: All In</p>
  <p class="artist">Artist: Fox Stevenson</p>
  <p class="genre">Genre: Drum &amp; Base</p>
  <p class="length">Length: 00:02:00</p>
  <p class="bpm">Beats per minute: 175</p> 
        <div class="circle" style="width: 87.5px; height: 87.5px; background-color: rgb(78, 101, 178);"></div>
</div>

And my JavaScript has the following code, currently adding the colors:

if($('.genre').text().indexOf('Drum & Base') >= 0) {
        $('#song').find('.circle').css({
            'backgroundColor': '#4E65B2'
        });
    }

Since I want to write that as dynamic as possible I was wondering if there is a smarter way to do that instead of writing some if and else blocks.

Dave

2 Answers

Brent Suggs
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Brent Suggs
Front End Web Development Techdegree Graduate 21,343 Points

You might try assigning your needed elements to varibles for simplicity and then using a switch statement for your genres in order to have one function for all genres.

Javascript Switch Statements

Dave Six
Dave Six
8,366 Points

Thanks! That looks like what I've been looking for!