Search code examples
javascriptonmouseoverqueryselector

QuerySelectorAll div and change its width onmouseover Javascript


I'm new to this and I'm trying to select multiple .card in my html (the share with gray background color)

Card

and change its width onmouseover, I also have contents that are in display:none and make all appear onmouseover using javascript, this is the code I have. Thank you for understanding.

var x = document.querySelectorAll(".card");
var i;

for (i = 0; i < x.length; i++) {
    x[i].style.width = "300px";
}

x.onmouseover = () => {
    x.style.width = "300px";
};


Solution

  • .querySelectorAll(".card") will return a collection of .card elements, so

    x.onmouseover = () => { ... };
    

    won't work.

    You have following options to do what you want.

    • Add mouseover event on all .card elements by looping over the collection returned by .querySelectorAll()

      const cards = document.querySelectorAll('.card');
      
      cards.forEach(card => {
        card.addEventListener('mouseover', (event) => {
          if (event.target.matches('.card')) {
            event.target.style.width = '150px';
          }
        });
      });
      .card {
        background: blue;
        width: 100px;
        height: 100px;
        margin: 10px;
      }
      <div class="container">
        <div class="card"></div>
        <div class="card"></div>
      </div>

    • Add mouseover event on the common parent element of all .card elements and using Event.target property, increase the width of the .card element which triggered the mouseover event

      const container = document.querySelector('.container');
      
      container.addEventListener('mouseover', (event) => {
        if (event.target.matches('.card')) {
          event.target.style.width = '150px';
        }
      });
      .card {
        background: blue;
        width: 100px;
        height: 100px;
        margin: 10px;
      }
      <div class="container">
        <div class="card"></div>
        <div class="card"></div>
      </div>

    • Do this via CSS using :hover pseudo-class.

      .card {
        background: blue;
        width: 100px;
        height: 100px;
        margin: 10px;
      }
      
      .card:hover {
        width: 120px;
      }
      <div class="card"></div>
      <div class="card"></div>

    P.S: Unlike :hover, when any .card element's width is increased on mouseover event, it doesn't resets back to original width when mouse pointer moves out of that .card element. If you need to do that and you don't want to use :hover pseudo-class, you will need to add mouseout event as well.