Guide to making a sliding animation appear when hovering over a menu using jQuery

I have noticed a common feature on many websites, but I am unsure of how to explain it.

At times, there are sliding elements in the navigation, like an arrow under menu items that moves when the user hovers over different links.

Here is an example of a simple menu:

<ul>
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link number 2</a></li>
    <li><a href="#">Link 3</a></li>
    <li><a href="#">Link something 4</a></li>
    <li><a href="#">Link 5</a></li>
</ul>   

Along with some jQuery (though achieving the same effect with simple CSS :hover is possible):

jQuery('ul li a').hover(function() {
    jQuery('a').removeClass('active');
    jQuery(this).addClass('active');
});

There is also a working jsfiddle provided:

http://jsfiddle.net/8EvhK/

Currently, the background color changes to red on hover. I would like this background to smoothly slide and transform (width) between these buttons as I hover.

How can I achieve something like this? I have searched for tutorials without luck.

Thank you!

Answer №1

  1. Use jquery's append function to add a new element to the menu.

    $('ul').append('<div id="slider"></div>');
    
  2. When any menu item is hovered over, use the animate function to move and resize the new element to match the selected menu item.

    $('ul li a').hover(function(){
    
        var left = $(this).parent().position().left;
        var width = $(this).width();
    
        $('#slider').stop().animate({
            'left' : left,
            'width' : width
        });
    });
    
  3. Reset the slider back to its original state.

    var left = $('ul li:first-child a').parent().position().left;
    var width = $('ul li:first-child a').width();
    $('#slider').css({'left' : left, 'width' : width});
    
  4. Add some CSS styling for the slider.

    #slider {
        position:absolute;
        top: -5px;
        left: 0;
        height: 100%;
        width: 0;
        padding: 5px 15px;
        background-color: #f00;
        z-index:-1;
    }
    

Check out the demonstration on this live fiddle: http://jsfiddle.net/5wPQa/2/

Answer №2

To create this type of animation, you can utilize CSS transitions:

ul li {
    display:block;
    padding: 5px 15px;
    background-color: #333;
    color: #fff;
    text-decoration: none;
    width:50%;
    -moz-transition: width 1s; /* Firefox 4 */
    -webkit-transition: width 1s; /* Safari and Chrome */
    -o-transition: width 1s; /* Opera */
}

ul li:hover{
    width:100%;
}

Take a look at this example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Cordova's ng-route functionality issue

I am currently working on an Angular application that includes the following code: // app.js var rippleApp = angular.module('rippleApp', ['ngRoute', 'ngAnimate', 'ngAria', 'ngMaterial']); // configure ou ...

Choose an identifier from a CSS class

I've been experimenting with a code pen that I stumbled upon: http://codepen.io/surjithctly/pen/pLDwe When I encase the checkbox in a div with the class "mynav," it stops functioning as intended. How do I implement the specified styling for the check ...

Retrieve the image by its unique identifier while viewing a preview of the image before it is uploaded

Below is the script I am using to preview an image before it is uploaded. The HTML structure looks like this: <div> <img id="image" src="#"> </div> <input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(th ...

Expanding content will not cause Flexbox to stretch

I am facing an issue with a container that includes a header tag and a div. The height of the div is set to 100vh, causing it to consume all available space. Within the div, there are two additional divs. Everything works as expected until I add more conte ...

Place a div element immediately following a table row in the HTML document

Welcome to my hotel and cabin availability page! I've created a PHP query that displays the available hotels and cabins in a table format. However, I want to enhance the user experience by displaying a Google Maps location and some pictures of each ho ...

Creating a flexible route path with additional query parameters

I am facing a challenge in creating a unique URL, similar to this format: http://localhost:3000/boarding-school/delhi-ncr However, when using router.push(), the dynamic URL is being duplicated like so: http://localhost:3000/boarding-school/boarding-school ...

Issues with JSON data not functioning properly when using file system in JavaScript

When attempting to parse a JSON file, I encountered some errors. The file is located in a directory within my JavaScript file, under the 'fs' in a folder named "recipes." Within this folder, there are 3 JSON files, each representing a separate ob ...

Vercel deployment issue: Hidden input values not being detected as expected

Whenever I attempt to update the data on Vercel, an error message is displayed: invalid input syntax for type uuid: "undefined" - unable to save Oddly enough, the data updates successfully when done locally. This is how I submit the form: <form onSu ...

jQuery form validation with delay in error prompts

I am experiencing a strange issue with my HTML form validation function. It seems to be showing the alert div twice, and I can't figure out why this is happening. Adjusting the delay time seems to affect which field triggers the problem. Can anyone sp ...

Exploring the ins and outs of flexbox and utilizing overflow:auto

In my current situation, I have successfully resolved all cases but am now seeking assistance in debugging my mental model. Specifically, I am focusing solely on Chrome for the sake of simplicity. Within my nested "holy grail-ish" flexbox layouts, I have ...

When using React-hook-form, you need to tap twice to delete the last character in the input field, and double tap to enter the first

I have been using React Hook Form to validate my form with multiple inputs. Everything works perfectly, except I noticed one issue where I have to press the backspace key twice to delete the last character and also twice to enter the first character. For e ...

What is the best way to position images and URLs in div elements using CSS?

Currently, I am on a journey to become a Front End Developer through Udacity. As part of my learning process, I have a project that needs to be submitted. Unfortunately, I encountered some issues that I couldn't resolve on my own. Specifically, I&apos ...

What strategies should be employed to manage data-driven input in this particular scenario?

In the process of creating a small webpage, I have designed 2 navigation panels - one on the left and one on the right. The leftNav panel contains a list of different flower names. While the rightNav panel displays images corresponding to each flower. A ...

What could be causing the span tag to not have CSS applied and the background image to not be displaying

The header I have created, shown in the image, is facing two issues. Firstly, I am unable to add ellipsis to the span tag even though I used it. I want the ellipsis to appear when the screen resolution is small. Secondly, the image uploaded is not displayi ...

What is the best way to create a slideshow using an IFrame?

Currently seeking a solution for an iframe slideshow that can smoothly transition between multiple HTML iframes. I have a total of 5 iframes that need to rotate automatically and continuously. Any suggestions on how to build a lively and dynamic iframe sl ...

Basic image scrolling gallery implemented using jQuery - without the need for any external plugins

Is there a way to create an image gallery without relying on jQuery plugins? Are there any specific jQuery functions that can help me create a custom image scroll feature? Does anyone have recommendations for best practices in this scenario? Whether it ...

Unable to set up npm for node-resemble on macOS

Issue Encountered: Error installing node-resemble package due to missing README data and configure errors. npm install failed with exit status 1. ...

Error Encountered - Node.js application experiencing issues in passport login functionality

I'm in the process of developing a login application using nodejs and incorporating passport js for authentication. The app is connected to a local MySql database and utilizes sequelize as its ORM library. Within my user model, I've implemented ...

Using z-index to position a paragraph element behind other elements in a webpage

I am facing a challenge where I want to hide a paragraph within an element, and layer it behind another element. Despite my attempts with z-index, I have been unsuccessful in achieving this effect between the elements. Could someone shed some light on why ...

Extract keys from the string

Is there a better way to extract keys from a string? const {Builder, By, Key, until} = require('selenium-webdriver'); ... const obj = {val: 'Key.SPACE'} if(obj.val.startsWith('Key.'))obj.val = eval(obj.val); (...).sendKeys(obj ...