Adjust the width of menu options using jQuery

One issue I am facing is with the menu on my homepage. I would like the menu options to enlarge upon hover, and while I have achieved this effect, there is a flaw in the animation:

When I move my cursor away before the animation completes, the option abruptly stops and deducts 30 pixels from its width, causing it to intersect with other animations and yielding inaccurate results.

For example:

If I quickly hover over menu option 1, it expands slightly, let's say by 10 pixels. But as I move away, the width decreases by 30 pixels, resulting in a smaller button size overall.

I am looking for a way to track the movement during the hover animation and only reduce the width by that amount when the cursor leaves. Or, perhaps there is a simpler solution available...

Below is the code snippet in question:

    
$('.menu_option').hover(

    function() {
        var w = $(this).width()+30+"";
        $(this).stop().animate({ width:w}, 150, 'easeOutQuad');
    }, function() {
        var w = $(this).width()-30+"";
        $(this).stop().animate({ width:w}, 150, 'easeOutQuad');
    });

Answer №1

To maintain the original width of an element, you can create a new variable to store the initial width and then revert to it when necessary:

Here is the JavaScript code:

var originalWidth = $('.menu_option').width();
$('.menu_option').hover(function () {

    var newWidth = $(this).width() + 30 + "";
    $(this).stop().animate({
        width: newWidth
    }, 150, 'easeOutQuad');
}, function () {
    $(this).stop().animate({
        width: originalWidth
    }, 150, 'easeOutQuad');
});

http://jsfiddle.net/Hive7/qBLPa/6/

Answer №2

Ensure the previous animation is finished before the width calculation

$('.menu_option').hover(function () {
    var $this = $(this).stop(true, true);
    var w = $this.width() + 30;

    $this.animate({
        width: w
    }, 150, 'easeOutQuad');
}, function () {
    var $this = $(this).stop(true, true);
    var w = $this.width() - 30 + "";

    $this.animate({
        width: w
    }, 150, 'easeOutQuad');
});

Example: Fiddle

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

Is there a way to incorporate my JavaScript code into my page.jsx file efficiently?

Can I integrate this javascript code from a .js file into my .jsx file seamlessly? const { exportTraceState } = require("next/dist/trace"); const toggleBtn = document.querySelector('.toggle_btn') const toggleBtnIcon = document.querySe ...

Struggling with D3.js Angular CLI where Scope disappears within the tick() function?

Hey everyone, I'm currently in the process of incorporating a D3 visualization network graph into an Angular CLI project (http://bl.ocks.org/mbostock/1153292) using the ng2-nvd3 component. Here's the Angular component: import { Component, OnIn ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

CFGRID Binding Issue: Element Not Located in CF11 Compared to CF2018

After spending some time tinkering with this issue, I finally found a solution that worked for me. I decided to share it here in the hopes that it might help others save some time. In ColdFusion 11, my binding parameter looked like this: <cfset args.b ...

Issue with Jquery checkbox calculator constantly displaying Not a Number (NaN)

I'm facing an issue with jQuery. The Custom Wpform Checkbox Field is returning NaN. HTML <div class="wpforms-payment-total"> $ 85 </div> <input type="checkbox" name="myBox2" size="1 ...

The validation process does not accept any values from the input

Currently, the validation function is not accepting any values in the input for current balance. Is there an alternative method to verify the value in the input field? Check out this JSFiddle link Here is the function under question: function isValid(ent ...

Struggling to align a search box with other items in a custom navbar using Bootstrap 4?

I created a unique navigation bar using Bootstrap 4's grid system. The navbar is designed with two sections: one for the navigation items on the left and another for the search box on the right. Unfortunately, I am facing an issue where the search box ...

PHP: When MySQL is not returning results and an undefined variable is causing issues

Currently, I am engaged in a project where I need to fetch some data from the database and display it within a form. Although my SQL query seems correct when reviewed in the SQL log, MySQL is not returning any results. I am seeking assistance on how to ret ...

A beginner's guide to integrating ng-class into a directive template using AngularJS

I have been attempting to achieve something similar to the following: template: "<div ng-if=\"successData\" ng-class=\"{ 'bounceInDown': successData == true,bounceInDown: successData == false}\" style=\"border-radius ...

Using a modal within a map function: Tips and tricks

I've been working on a Gallery application using React.JS and Reactstrap. The application uses the map() function to display each piece of art in a Card. Each card has a button that triggers a modal to show more data from the map function. However, I& ...

Shifting an image outside of the container in a Bootstrap 4 card header

I am attempting to create a design similar to this: https://i.sstatic.net/OR4Em.png I am currently using Bootstrap 4 cards, but I am struggling to figure out the best way to move the icon/image outside of the Cards header. I have experimented with differe ...

Facing an issue where WordPress AJAX is not showing the expected content

Currently, I am in the process of creating a WordPress website that will feature an initial display of two rows of images. Upon clicking a button, two more rows should dynamically appear. There are four key files involved in this project: case-study-ca ...

JavaScript appends a backslash character to a CSS class

I am attempting to populate index.html with the contents from an array using a JavaScript loop. However, I am encountering an issue where a CSS class for picture formatting is displaying some odd characters when rendered in the latest version of Firefox. ...

Interactive chart embedded within a container

I have recently designed a card using Bootstrap and I would like to include a table with some data in it. However, I am facing an issue where the table data spills out of the card when I reduce the screen size for responsiveness testing. Could someone pl ...

Creating a sleek and functional dashboard using HTML and leveraging the power of Bootstrap 4

I'm working on styling my HTML dashboard with Bootstrap 4. I want the text to be big and have minimal white space, but not too cluttered. <html> <head> <meta charset="utf-8"> <meta name="viewport" conte ...

Save user entries in a database array

I'm working on developing a platform for advertisements where users can create detailed profiles with images. To achieve this, I need to store the information in an array within a backend database for future retrieval. Below is an example of the backe ...

Display a picture retrieved from a POST request using Angular and a Spring Boot backend

Recently, I've been delving into the world of HTTP requests. My latest task involves uploading an image from the client and sending it to the server using a POST request. When testing this process in Postman, everything works smoothly as I receive th ...

What is the process for removing a Discord user using Node.js?

I've been working on creating a discord bot using node.js, but I'm facing an issue where nothing happens when I try to use a command. The console doesn't log anything except for the bot coming online. const Prefix = '$'; bot.on(&a ...

Guidelines for setting up individual click events for each button using Jquery

I'm encountering an issue with the following jQuery code. While I am able to successfully find each button by its id, clicking the button does not load the specified URL. How can I adjust the jQuery so that clicking the button triggers the URL loading ...

Continuing to use a function multiple times may lead to a type error as it is not a

My program is designed to be a quiz where users have to answer questions. After answering, they will see a summary and then get the option to submit or redo the questions. The issue arises when users choose to redo a question. Upon redoing it, the summary ...