Reusable Cursor Hover Function In JavaScript

function hover(element, enter, leave){
  element.addEventListener('mouseenter', enter)
  element.addEventListener('mouseleave', leave)
}

You can then pass your element and callback functions like so.

hover(document.querySelector('h1'), e => {
  // On hover
  e.target.classList.add("logo__container--hover")
}, e => {
  // On exit hover
  e.target.classList.remove("logo__container--hover")
})

You can reduce the lines of code too by modifying the hover function.

function hover(element, className){
  element.addEventListener('mouseenter', e => element.classList.add(className))
  element.addEventListener('mouseleave', e => element.classList.remove(className))
}

Then use it like so.

hover(document.querySelector('h1'), "logo__container--hover")

You can reuse this now for multiple elements scalably.

Source

Leave a Reply

Your email address will not be published.