Search code examples
javascriptarraysaddeventlistenermouseover

div with added class in JS not triggering a mouseover event over multiple elements


my inner-cursor is a circle that should grow to the size of the outer-cursor with the class of .grow when I set the mouseover event in JS. It doesn't trigger when I hover over specifically only buttons (it doesn't trigger at all). There are multiple buttons (it is a test calculator) all with the class of 'button'.

<div class="inner-cursor">
</div>

<div class="outer-cursor">
</div>

<button class="button" type="button" value="1" id="1">1</button>
<button class="button" type="button" value="2" id="2">2</button>
.inner-cursor {
    position: fixed;
    left: 10px;
    width: 10px;
    height: 10px;
    transform: translate(-50%, -50%);
    background-color: #627CE4;
    border-radius: 50%;
    pointer-events: none;
    transition: width 0.5s, height 0.5s;
}

.outer-cursor {
   position: fixed;
   left: 10px;
   width: 25px;
   height: 25px;
   transform: translate(-50%, -50%);
   border: 1px solid #627CE4;
   border-radius: 50%; 
   pointer-events: none;
   transition: 0.1s;
}

.inner-cursor.grow{
    width: 25px;
    height: 25px;
    transition: width 0.5s, height 0.5s;
}
let outerCursor = document.querySelector('.outer-cursor');
let buttons = document.querySelector('.button');

document.addEventListener('mousemove', moveCursor);

function moveCursor(e){
    let x = e.clientX;
    let y = e.clientY;


    innerCursor.style.left = `${x}px`;
    innerCursor.style.top = `${y}px`;

    outerCursor.style.left = `${x}px`;
    outerCursor.style.top = `${y}px`;
}

function growCursor(e){
    buttons.addEventListener('mouseover', function (){
        innerCursor.classList.add('grow');
    });
    buttons.addEventListener('mouseleave', function () {
        innerCursor.classList.remove('grow');
    })
};

My attempts included the above (which produced no result) and the following where I tried to make the buttons an array (which actually halts the div from following the cursor's movement anymore):


let buttons = Array.from(document.querySelectorAll('b'));

buttons.forEach((button) => {
    buttons.addEventListener('mouseover', () => {
            innerCursor.classList.add('grow');
});
buttons.addEventListener('mouseleave', () => {
    innerCursor.classList.remove('grow');
});
});

Thank you for any suggestions


Solution

  • error in your js code, it must be button and not buttons inside the forEach function

    // use either one here
    let buttons = Array.from(document.querySelectorAll('.button'));
    // added this innerCursor
    let innerCursor = document.querySelector('.inner-cursor');
    
    buttons.forEach((button) => {
        button.addEventListener('mouseover', () => {
            innerCursor.classList.add('grow');
        });
        button.addEventListener('mouseleave', () => {
            innerCursor.classList.remove('grow');
        });
    });