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

Having trouble integrating Bootstrap with Fullpage.js

After following this solution, I attempted to create a basic full-page layout using bootstrap. I aim to have a front end that scrolls like a full page, ensuring responsiveness. Folder Setup https://i.sstatic.net/ylZF8.png Code Snippet <!DOCTYPE htm ...

Jest: Issue with spyOn test failing despite async function being executed

Having trouble setting up a spyOn for an async function within a submodule. This issue is throwing me off because I've successfully implemented similar tests in the past. Here's an overview of the code: In routes.js: const express = require(&apo ...

Tips for setting up OpenLayers demonstrations on a personal server?

Currently, I'm working with an older version of OpenLayers (4.6.2) and find the provided examples extremely helpful for testing and reference purposes. However, the official web page with updated examples only includes the latest version. I am wonder ...

Storing a collection of items in an array using jQuery

Looking to organize list items from multiple lists of the same class into an array. For example: <ul class="myList"> <li>item 1</li> <li>item 2</li> </ul> <ul class="myList"> <li>i ...

Display a Google Map within a modal window following an Ajax request

I'm currently developing a website where I need to display a Google map inside a modal after an AJAX call. The modal is created using Bootstrap, but I'm facing an issue where the map remains blank once the modal is opened. An interesting observa ...

Firestore query is returning empty results upon page initialization, but provides data upon subsequent re-renders in React Native

ISSUE I'm encountering an issue where I am unable to fetch documents from a Firestore collection when the page loads. Despite executing the query multiple times during loading, it does not return any results. However, if I trigger the query by changi ...

Deactivate collapsing of active element in Bootstrap 5 accordion without using jQuery

Check out this example of a Bootstrap 5 Accordion element: <div id="accordion-1" class="accordion" role="tablist"> <div class="accordion-item"> <h2 class="accordion-header" role=& ...

Transforming a string into a proc using Ruby and Rails

Here's the scenario I'm dealing with. The current URL appears as follows: /categories/Art Using name = location.pathname.split('/')[2], I extract the Art part of the URL. Then, I send an AJAX request to the controller with the followi ...

Optical Character Recognition (OCR) tool

Does anyone have recommendations for a JavaScript OCR API that can easily be accessed via JavaScript? I'm searching for an API similar to this: upload an image along with the desired result type (e.g. numbers, objects, text, mixed, etc) and receive t ...

How to Create a Bootstrap 4 Footer that is Perfectly Centered

Struggling to grasp Bootstrap 4 specifically, I am focusing on learning how to center my footer, which consists of 2 rows. Despite my efforts, I can't seem to get the entire footer centered properly. Below is the current HTML code I am working with: ...

Tips for stopping a page from reloading when a link is clicked

I have implemented a script to enable AJAX on my blogger site using the jQuery Ajaxify plugin (https://github.com/swook/jquery-ajaxify-plugin). This allows users to listen to music via the player without experiencing interruptions while navigating through ...

Troubleshooting: Font-Face Won't Load on Any Browser

I'm completely new to using @font-face and I'm encountering some issues. Despite going through numerous posts and tutorials, I can't seem to get my fonts to load properly. I've tried activating and deactivating the font on the server, b ...

javascript retrieving JSON data through an API request from a redirected URL

I am retrieving JSON data from the Glitch API. Upon opening the link, it redirects to a different domain (the domain was changed from gomix.me to glitch.me) When using Postman for both HTTP requests, I receive identical JSON data. However, there is a d ...

Utilize the power of XMLHttpRequest to fetch and load numerous audio files, seamlessly integrating them for playback through the Web Audio

I am looking to create a web application that loads three different audio files, each one second long, in a specific order, and then merges them into a single Audio Buffer consecutively. To illustrate my goal, here is a sample code snippet: var AudioCo ...

Issue with Bootstrap flash alert CSS on mobile devices is not functioning properly

I am in the process of developing a Rails application. Within my app, I utilize Bootstrap's CSS for displaying flash messages on alerts. Instead of fully incorporating Bootstrap's CSS, I only integrate styles related to alerts in order to prevent ...

Automatically generating new lines of grid-template-columns with CSS grid

I am new to using grid in CSS and there are still some concepts that I don't quite understand. Below is the container I am working with: <section class="css-grid"> <div class="css-item"><img src="1.jpg" / ...

Is it possible to collapse and expand individual rows within the Material-UI DataGrid component?

Is there a way to create expand-collapse functionality for each row in Material-UI DataGrid? While I understand that we can achieve this with TableRow and manual rendering (Collapsible table), I am wondering if it is possible within the DataGrid component ...

What is the best strategy for positioning an anchor element within a list item using JSX or Bootstrap in a way that maximizes efficiency?

I have the following code snippet <li className = "list-group-item list-group-item-success" key ={todo.id}>{todo.text}<a style="float:right;" onClick={() => props.onEdit(todo)} className="edit-todo glyphicon glyphicon-edit" href="#"& ...

Handling a change event for a mat-datepicker in Angular 7 can be tricky, especially when its value is tied to an optional input parameter. Let's dive into how to

I've recently started working with angular development and encountered a challenge with a mat-datepicker. The value of the datepicker is connected to filterDate using [(ngModel)] as an @Input() parameter. I have implemented a handleChange event that e ...

How can you automate clicking a button and then performing a specific action through code?

In my current coding project, I am attempting to automate the process of clicking on a tab through a script in order to reveal additional divs on the webpage. Once these divs are revealed, I need to perform certain actions on them. My code currently looks ...