Skip to content

Instantly share code, notes, and snippets.

@clairefro
Last active March 13, 2024 20:34
Show Gist options
  • Select an option

  • Save clairefro/7522e1d1eb69863e5c3647f1ca849223 to your computer and use it in GitHub Desktop.

Select an option

Save clairefro/7522e1d1eb69863e5c3647f1ca849223 to your computer and use it in GitHub Desktop.

Unit 3 Project: HTML, CSS, JavaScript

Adding an event listener to an HTML element to change CSS style

index.js

<div class="opening-screen">I am hungry</div>

<button class="option-one-button">Sleep</button>
<button class="option-two-button">Eat a sandwich</button>

<div class="option-one-screen">Now I'm starving!!</div>
<div class="option-two-screen">Yum!</div>

script.js

  // Store your HTML elements as variables
  
  let openingScreen = document.querySelector('.opening-screen');
  
  let optionOneScreen = document.querySelector('.option-one-screen');
  let optionOneButton = document.querySelector('.option-one-button');
  
  let optionTwoScreen = document.querySelector('.option-two-screen');
  let optionTwoButton = document.querySelector('.option-two-button');

  // Add event listeners to the buttons
  
  optionOneButton.addEventListener("click", function() {
    openingScreen.style.display = 'none';  // hide opening screen
    optionOneScreen.style.display = 'block';  // show option one screen
  });
  
  optionTwoButton.addEventListener("click", function() {
    openingScreen.style.display = 'none';  // hide opening screen
    optionTwoScreen.style.display = 'block';  // show option two screen
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment