-4

Im trying out javascript and wanting to add a click event listener to a h1. very simple, click on h1 and it changes colour. it currently works, but when i click anywhere on the page. i only want it to change colour when the h1 is clicked. Any ideas, and keeping close as possible to my code. and only vanilla javascript. thanks

<h1 id="button">HI</h1>


<script>
  document.addEventListener("click", (event)=>{
    const button = document.getElementById("button")
    button.classList.add("red")
  });
</script>


<style>
  #red{
    color:red;
  }
</style>
b.herring
  • 563
  • 2
  • 18

2 Answers2

2

There are a few issues with your code above.

Your CSS is written to target the id instead of the class.

As another post stated you are currently targeting the entire document with your eventListener, which is why any click is triggering the event.

Something along the lines of this code pen should target a single element: https://codepen.io/justindunham/pen/KbQymj

document.querySelector('#button').addEventListener("click", (event)=>{
   event.target.classList.add("red");
});
jdunham
  • 439
  • 3
  • 6
0

Ok so you have a (few) options to chose between.

One of them is quite simple but not that efficient. In your original code you have attempted to use multiple IDs on the same element, which is not allowed. So, a workaround for that would be to use javascripts style property in order to set the color of your element.

document.getElementById("button").addEventListener("click", function(){
    document.getElementById("button").style.color = "#ff0000";
});
<h1 id="button">HI</h1>

Another options is that you could use a class to specify styling for your element and (if necessary: the added class can be removed) a toggle effect can be achieved.

document.getElementById("button").addEventListener("click", function(){
 let element = document.getElementById("button");
 if(!element.classList.contains("h1Color")){
  element.classList.add("h1Color");
 } else {
  element.classList.remove("h1Color");
 }
});
.h1Color {
 color: red;
}
<h1 id="button">HI</h1>

References:
https://stackoverflow.com/a/5898748/6212957
https://www.w3schools.com/howto/howto_js_add_class.asp#midcontentadcontainer
https://www.w3schools.com/howto/howto_js_remove_class.asp#midcontentadcontainer

Feelsbadman
  • 1,163
  • 4
  • 17
  • 37