Notion app logo
Struggling to stay organized and effective? Learn to master your time and tasks with the Effectively Notion course!

Highlight Navigation Element Using JavaScript

How to highlight a navigation element using JavaScript

2013-10-24

On Stack Overflow I found a question: How can I make my CSS menu's hover states move horizontally for UX purposes?

Unfortunately, this solution can't be purely CSS, it needs JavaScript to work.

It helps to approach this problem by thinking about the flow of the interaction:

  • A user hovers over an element in a navigation bar.
    • If this is the first hover into the navigation bar, move a highlighter to the current navigation element's position and width.
    • If there was another element that has been hovered already, move the highlighter to the element's position and width.
  • The user moves out of the navigation bar.
    • Move the highlighter out of sight.

The Problem

With a pure CSS solution, one element's interaction can effect another unnested element's actions.

So what I proposed was to use CSS for the transition, and javascript to get the current position and width of the anchor that's hovered, then update the highlighter's style values to the new anchor's values:

Here's a JSFiddle of what the asker was trying to achieve: https://jsfiddle.net/realchaseadams/Dm9Eu/4/

And the gist (https://gist.github.com/chaseadamsio/7281682) for the code:

A Solution

You'd inject the highlighter on the page with javascript, then have a fallback if CSS3 transitions aren't supported (most easily done using jQuery). On my personal projects, I'm not really concerned if visitors get cool flashy animations, so I would be happy for the bar to just move to the position without being a smooth transition.

How would you have solved this problem? Create a JSFiddle or a gist and share it, I'd love to see how other people solve this problem!

Original Question: How can I make my CSS menu's hover states move horizontally for UX purposes? (StackOverflow Question)

Photo of Chase Adams

Hey, I'm Chase. I help aspiring entrepreneurs and makers turn their ideas into digital products and apps.

Freebies

Vector Arrow Scribbles
banner image for figma vector arrows scribbles

A figma community project of vectorized hand-drawn arrows.

Go To Figma
Vector Line Scribbles
banner for figma vector line scribbles

A figma community project of vectorized hand-drawn lines.

Go To Figma
Vector Shape Scribbles
banner image of figma vector shapes scribbles

A figma community project of vectorized hand-drawn shapes.

Go To Figma

Subscribe to my Newsletter

Every other week I publish the Curiously Crafted newsletter.

In it, I explore the intersection of curiosity and craft: the people who make stuff, what they make and the way they pursue the craft of making.

Online

I'm on almost all social media as @curiouslychase.

The curious logo of Chase Adams: glasses and a bow tie.stay curious.