Javascript mouseover only working on first element

Viewed 3880

I'm trying to have an icon change color everytime an input box is hovered. The problem is it is only changing the background when hovering the first input textbox, not the other two.

I'm trying to get this effect without jquery.Thanks in advance for your help !

var input = document.querySelector ('input');
var icon = document.querySelector ('img');

input.addEventListener ('mouseover', function hover(){
  icon.style.background = '#D46855';
});
input.addEventListener ('mouseleave', function leave(){
  icon.style.background = '#81D455';
  
});
@import url('https://fonts.googleapis.com/css?family=Indie+Flower');


body{
 background-image :url(https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/b0e53331516629.565449774c2d4.png); 
}
h1{
 font-family: 'Indie Flower', cursive;
  font-size:3em;
  color:#D46855;
  letter-spacing:5px;
}

#container{
  text-align:center;
  margin:10% auto;
  padding-top: 50px;
  border-radius:15%;
  width:80%;
  height:400px;
  position:relative;
  background-color : rgba(84, 193, 212, 0.56);
 box-shadow: 5px 5px 4px 5px rgba(84, 193, 212, 0.56);
}

img{
left: 0;
right: 0;
bottom: 0;
margin: auto;
  height:100px;
  width : 100px;
  position:absolute;
  top: -95%;
  border-radius:30px;
  background:#81D455;
}

input{
  width:200px;
  height:15px;
  font-size:1.2em;
  padding:10px;
  text-align:center;
  display:flex;
  margin:0 auto;
  margin-top:20px;
}
<div id = 'container'>
  <h1>To Do List</h1>
  <img src = "https://www.jamiesale-cartoonist.com/wp-content/uploads/cartoon-business-man-free1.png">
  <form>
    
    <input type = 'text' placeholder = 'item' id = 'list' </input>
    <input type = 'text' placeholder = 'item' id = 'list' </input>
    <input type = 'text' placeholder = 'item' id = 'list' </input>
  </form>
   </div>
</body>

Any advice would be appreciated (:

1 Answers

querySelector returns only the first element that is found.

As you have multiple input elements use querySelectorAll

var input = document.querySelectorAll('input');

Also as querySelectorAll returns multiple elements ( which is a node list of inputs in this case ) , you will have to attach the event handlers in a loop.

var inputs = document.querySelectorAll('input');
var icon = document.querySelector('img');

inputs.forEach(function(input) {
  input.addEventListener('mouseover', function hover() {
    icon.style.background = '#D46855';
  });

  input.addEventListener('mouseleave', function leave() {
    icon.style.background = '#81D455';

  });
});
Related