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

jQuery help: Why isn't my color variable storing.

JS fiddle here:

https://jsfiddle.net/rdrkeLx7/

I am trying to change the main color of the svg to the left based on the color of the list item selected. Can you spot what I am doing wrong?

The color will change if I add the selected class manually to the html, but it doesn't change when the selected class is added by javaScript. It doesn't seem to be storing the background color the variable though I can't see why it's not.

1 Answer

Codin - Codesmite
Codin - Codesmite
8,600 Points

Your jQuery for changing the fill color of .main-body is outside of the scope of the click function, so it isn't being called. Putting it in side fixes the problem.

var mainBodyColor = $(".main-body-select .selected").css("background-color");

//Change the selected color in the color picker list elements.
$(".main-body-select li").click(function () {
    //Deselect sibling elements
    $(this).siblings().removeClass("selected");
    //Select clicked element
    $(this).addClass("selected");
    //store color here
    mainBodyColor = $(this).css("background-color");
    $(".main-body").css("fill", mainBodyColor);
});

https://jsfiddle.net/jts15gg4/

Thank you so much. I thought stating the variable mainBodyColor at the beginning outside of the function would make that variable global, and also make changes to it global. Since this isn't the case, is there a way to make the changes to mainBodyColor usable in other functions? I need to brush up more on scope and functions.

And again thank you for your solution!

Codin - Codesmite
Codin - Codesmite
8,600 Points

Your variable mainBodyColor is still accesible in other functions because you defined it outside the scope of the function.

If you declared the mainBodyColor variable inside your click event function it wouldn't of been global. Even after the click event changes mainBodyColor in the function it is updating the value of the global variable and will be usuable outside of the functions scope.

The only reason it did not work before was because the line that updates the value of mainBodyColor's fill was outside the click event so it didn't know to update the value when the colour swatches were clicked.