Will McLean
Process diary

A vanilla JS structure for hover states on more than one element

Last modified: October 26, 2017
Created: September 25, 2017

If you want to do some crazy hover effects using javascript on multiple elements on a page then use this structure. This technique is useful if you want to use something from the mousemove event, like the mouse position.


function yourHovers() {
 
    let elements = document.querySelectorAll( '.classname' );
 
    for ( let element of elements ) {
        elementHover( preview );
    }
 
    function mousemoveHandler( event ) {
        // Do stuff
    }
 
    function mouseleaveHandler() {
        // Reset stuff
    }
 
    function elementHover( element ) {
        element.addEventListener( 'mousemove', mousemoveHandler );
        element.addEventListener( 'mouseleave', mouseleaveHandler );
    }
 
}

This is a Knowledge Base post.