Skip to content

bfiessinger/Vanilla-JS-Magic-Line-Navigation

Repository files navigation

Vanilla JS - Magic Line Navigation

original idea: https://css-tricks.com/jquery-magicline-navigation/

CodeFactor code style: prettier

Browser Support

Chrome Firefox IE Edge Opera Safari
< 15 ✔ 5+ ✔ 10+ ✔ < 15 ✔ < 23 ✔ 5.1+ ✔

To get IE Support below Version 10 (or any other browser that does not support Element.Classlist) use a Classlist Polyfill.

Dependencies

  • None

However you can implement every Animation Library like anime.js for the animations.

Features:

  • works with any animation Library like anime.js, velocity.js, GSAP, e.g.
  • works with CSS Transitions (no animation library required)
  • fully responsive
  • able to animate in any direction (left to right, top to bottom, diagonal)
  • pillmode & linemode

Usage

var myMagicLine = new magicLine(
  document.querySelectorAll('.magic-line-menu'),
  {
    navElements: 'a',                           // navigation element selector
    mode: 'line',                               // line or pill
    lineStrength: 2,                            // Thickness of the line
    lineClass: 'magic-line',                    // Classname to add to the line element
    wrapper: 'div',                             // the node that's being created as an element wrapper
    animationCallback: function (el, params) {  // might be either null or a callback function
      animationLibrary({
        targets: el,
        left: params.left,
        top: params.top,
        width: params.width,
        height: params.height
      });
    }
  }
);
myMagicLine.init();

Basic Setup

HTML

The most basic html structure to use is shown below:

<nav class="my-magic-line">
  <a>Magic</a>
  <a>Line</a>
  <a class="active">is</a>
  <a>awesome</a>
</nav>

CSS

Required styling

.init-magic-line,
.magic-line-inner {
  position: relative;
}

.magic-line {
  z-index: -1;
  position: absolute;
}

.magic-line-css-transition {
  transition: all .2s ease-in-out;
}

Javascript

var myMagicLine = new magicLine('.my-magic-line');
myMagicLine.init();

Options

Option Value Default
navElements a query Selector, you can even define multiple like 'a, span' 'a'
mode might be either 'line' or 'pill' 'line'
lineStrength thickness of your line in px 2
lineClass The classname of the floating-line element 'magic-line'
wrapper DOMNode to be inserted as a wrapper 'div'
animationCallback a callBack Function used for animation null

This is how it looks like

Alt text

Filesize

  • Minified Version:

    • 2.58 KB (1.07 KB gzipped)
  • Non Minified Version

    • 7.49 KB (2.12 KB gzipped)

DEMO

Check out the Demo on Codepen