vendredi 14 juin 2019

How to create a dropdown that changes the background of your website using Javascript?

I'm working on an assignment that requires the background of the website to change based on the selected dropdown option. ie. If 'NYC' is selected, the background changes to a photo of NYC, where the relative URL of the image is already in CSS.

I am required to add the city options using an array with values 'NYC, SF, LA, ATX, SYD' using a 'for loop' in JS, instead of adding it directly to the HTML. I am also asked to specifically incorporate $.append(), $.attr(), $.val(), $.change() and the if/else if statement in the JS code.

I've tried writing the code from scratch along with help from other sources but the pre-written codes don't work with my specific requirements. I understand the HTML and CSS but I'm still very new to Javascript and JQuery. Enough to know it's wrong. I definitely have not gotten the right code for the 'for loop' or the dropdown menu thus far.

Here is the HTML:

<body>
<header>
    <div class="title">
        <h1>CitiPix</h1>
        <p>Your Cities, Your Pix</p>
    </div>
</header>
    <div class="container">
    <form>
        <select id="city-type">
            <option>Select a City</option>
        </select>
    </form>
    </div>
</body>

This is the JS I have so far:

$(document).ready(function(){

$('.container').click(function(event){
  var cityName = ['NYC, SF, LA, ATX, SYD'];
  $("#city-type").append(var cityName);
  cityBackground(city);
  if (!event.target.matches('#submit-btn')) {
  var dropdowns = document.getElementsByClassName('city-type');
  var i;
  for (i = 0; i < container.length; i++) {
}}}

$('select').change(displayVals);
displayVals();

function displayVals() {
    var cityName = $( "#city-type" ).val();

function cityBackground(citytype){
    if (citytype === 'NYC') 
  {
      $('body').attr('class', 'nyc');
  }
  else if (citytype === 'SF')
  {
     $('body').attr('class', 'sf');
  }
  else if (citytype === 'LA')
  {
     $('body').attr('class', 'la');
  }
  else if (citytype === 'ATX')
  {
     $('body').attr('class', 'austin');
  }
  else if (citytype === 'SYD')
  {
     $('body').attr('class', 'sydney');
  }
  }
}

The dropdown menu is not showing, it just shows the "Select a City" text and the whole dropdown code is not running. The .change and .val requirements are also confusing as to where its suppose to fit in the code.

Aucun commentaire:

Enregistrer un commentaire