# Changing background colour

I am currently changing the background colour of a sidebar each time a menu item is clicked using the following code:

$( 'a[href = "#masthead"' ).click(function() {$('#sidebar').css('background-color', '#3b6dac');
});

$( 'a[href = "#section2"' ).click(function() {$('#sidebar').css('background-color', '#23d4d7');
});

$( 'a[href = "#section3"' ).click(function() {$('#sidebar').css('background-color', '#59d078');
});


It does what I want, but I am relatively new to JavaScript and jQuery, and I imagine there is likely to be a better way...

jsFiddle

• Are you open to changing the html? – RobH Feb 6 '15 at 10:43
• Yes certainly if it makes things cleaner. – Sam Feb 9 '15 at 4:33

You can do something like this:

<ul class="list-unstyled main-nav">
<li><a href="#section2" data-bg-color="pink">Section 2</a>
<li><a href="#section3" data-bg-color="orange">Section 3</a>
</ul>


and js:

$( 'a[data-bg-color]' ).click(function() {$('#sidebar').css('background-color', $(this).attr("data-bg-color")); });  or if you cannot change html: $( '.main-nav a' ).click(function() {

var color = "blue"; //default;

switch($(this).attr("href")) { case '#masthead' : color = "blue"; break; case '#section2' : color = "pink"; break; case '#section3' : color = "orange"; break; }$('#sidebar').css('background-color', color);
});


# Improved solution

If you can do the first option but if you don't like to write in HTML the color of background (according to best practice, the style should be inside css), then you can use the same approach but using the class to add on sidebar.

For example:

<li><a href="#masthead" data-sidebar-class="master">Masthead</a>
<li><a href="#section2" data-sidebar-class="section2">Section 2</a>
<li><a href="#section3" data-sidebar-class="section3">Section 3</a>


and js:

$( 'a[data-sidebar-class]' ).click(function() { // http://stackoverflow.com/questions/2644299/jquery-removeclass-wildcard$('#sidebar').removeClass(function (index, css) {
return (css.match (/(^|\s)sidebar-\S+/g) || []).join(' ');

.sidebar-master { background-color: blue }