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
You can do something like this:

&lt;ul class="list-unstyled main-nav"&gt;
  &lt;li&gt;&lt;a href="#masthead" data-bg-color="blue"&gt;Masthead&lt;/a&gt;
  &lt;li&gt;&lt;a href="#section2" data-bg-color="pink"&gt;Section 2&lt;/a&gt;
  &lt;li&gt;&lt;a href="#section3" data-bg-color="orange"&gt;Section 3&lt;/a&gt;
&lt;/ul&gt;


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:

&lt;li&gt;&lt;a href="#masthead" data-sidebar-class="master"&gt;Masthead&lt;/a&gt;
&lt;li&gt;&lt;a href="#section2" data-sidebar-class="section2"&gt;Section 2&lt;/a&gt;
&lt;li&gt;&lt;a href="#section3" data-sidebar-class="section3"&gt;Section 3&lt;/a&gt;


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(' ');
    }).addClass("sidebar-"+$(this).attr("data-sidebar-class"));

});


and css:

.sidebar-master { background-color: blue }
.sidebar-section2 { background-color: pink }
.sidebar-section3 { background-color: orange }


demo: http://jsfiddle.net/9vtxutth/1/