Search code examples
javascriptonmouseover

How do I add class of scaleUp to multiple span elements on an event listener of onmouseover


I want to add a class of scaleUp to all span elements on an event listener of onmouseover.

I think this can be achieved through forEach() method but I am unable to do it

My HTML: -

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>
        <span>H</span>
        <span>E</span>
        <span>L</span>
        <span>L</span>
        <span>O</span>
        <span class="special">!</span>
    </h1>

    <script src="app.js"></script>
</body>
</html>

My current Javascript code:-

const letters = document.querySelectorAll('span');

for (var i = 0 ; i < letters.length; i++) {
   letters[i].addEventListener('onmouseover' , function(){
    letters.classList.add('scaleUp');
   }) ; 
}

I know my code has a lot of problem but kindly help. Thanks in advance


Solution

  • There are a couple of issues:

    • 'onmouseover' should be 'mouseover'
    • inside the event you are referencing letters instead of this

    I've added a small snippet to show you how it can be done.

    const letters = document.querySelectorAll('span');
    
    for (var i = 0 ; i < letters.length; i++) {
       letters[i].addEventListener('mouseover' , function(){
         this.classList.add("scaleUp");
       }) ; 
    }
    .special {
      color: red;
    }
    
    .scaleUp {
      color: blue;
    }
        <h1>
            <span>H</span>
            <span>E</span>
            <span>L</span>
            <span>L</span>
            <span>O</span>
            <span class="special">!</span>
        </h1>