The reason behind this javascript background changer project is I haven’t done a JavaScript project in a while and I wanted to start off with something relatively easy. I also thought it would be neat to learn how to change the background image using a dropdown element.

Brainstorming

Before starting a javascript background changer project I like to sit down and jot down the steps needed to do this complete it.

  1. Create a hero
  2. Add background image to hero
  3. Add a dropdown to the hero with different values
  4. Create different classes with different background images

So first, I would need to create a hero image and I would initially add a background image to it. I would then need to add a dropdown on this hero image. The drop down would contain a few values that would match class names I create. Each class name would have a different background url. Upon selection of each value in the dropdown it would change to the corresponding class. The background would then change.

HTML

To create the javascript background changer I decided to use Bootstrap because then I can use the jumbotron element for the hero image. After adding in the jumbotron I added in a drop down element. The dropdown element contains five values — forest, stars, lake, stream, and mountain. Each of these match up with a class in my CSS file. I added an id to the dropdown element and the jumbotron to be able to grab both of these in my JavaScript file.

Copy to Clipboard

CSS

In the CSS file for the javascript background changer I added in 5 classes of forest, stars, lake, stream, and mountain. Each of these classes has a different background image and formatting for the image. I added in some extra css to have the image take 100% of the screen’s height and to make the image stretch to take up the whole jumbotron width. Lastly, I added a width to the bootstrap dropdown and from control elements.

Copy to Clipboard

JavaScript

To make the JavaScript background changer we only need 3 lines of code. I created an on change function for the dropdown by grabbing the dropdown element by its id. When a change occurs on the dropdown (ie selecting a different value) the function will grab the jumbotron by its id and add the class from the dropdown (this.value) and add the jumbotron class back in, so we don’t lose bootstrap jumbotron styling.

Copy to Clipboard