Direction-aware Lava Lamp Hover Effect

Category: Animation , Javascript | May 1, 2019
Author: Tobias Reich
Views Total: 243
Official Page: Go to website
Last Update: May 1, 2019
License: MIT

Preview:

Direction-aware Lava Lamp Hover Effect

Description:

A simple script that adds a Lava Lamp style, direction-aware underline effect to navigation links on mouse hover.

How to use it:

Create a navigation menu for your site.

<nav>
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Contact</a>
</nav>

Apply a sliding underline effect to the links.

a {
  text-decoration: none;
}

a::after {
  --scale: 0;
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 100%;
  height: 3px;
  background: #4c81c9;
  -webkit-transform: scaleX(var(--scale));
          transform: scaleX(var(--scale));
  -webkit-transform-origin: var(--x) 50%;
          transform-origin: var(--x) 50%;
  transition: -webkit-transform 0.3s cubic-bezier(0.535, 0.05, 0.355, 1);
  transition: transform 0.3s cubic-bezier(0.535, 0.05, 0.355, 1);
  transition: transform 0.3s cubic-bezier(0.535, 0.05, 0.355, 1), -webkit-transform 0.3s cubic-bezier(0.535, 0.05, 0.355, 1);
}

a:hover::after {
  --scale: 1;
}

The main JavaScript.

document.querySelectorAll('a').forEach(elem => {

  elem.onmouseenter =
  elem.onmouseleave = e => {

    const tolerance = 5;

    const left = 0;
    const right = elem.clientWidth;

    let x = e.pageX - elem.offsetLeft;

    if (x - tolerance < left) x = left;
    if (x + tolerance > right) x = right;

    elem.style.setProperty('--x', `${x}px`);

  };

});

You Might Be Interested In:


Leave a Reply