Animate sliding bar to move from the left using jQuery

I am currently experiencing an issue with a sliding animation on mouseover in the navigation. The animation works fine, but the problem arises when I hover over any menu item - the sliding bar starts from the very left instead of starting where the navigation items begin.

For reference, here is the JSFiddle

$(".mega-navigation--level-one").append("<span class='nav-hover'></span>");
var $magicLine = $(".nav-hover");
    $magicLine
        .width($(".active > a").innerWidth())
        .css("left", $(".nav-hover").position().left - 400)
        .data("origLeft", $magicLine.position().left)
        .data("origWidth", $magicLine.width());

    $(".mega-navigation--level-one > li").hover(function () {
        $el = $(this);
        leftPos = $el.position().left + 20;
        newWidth = $el.width();

        $magicLine.stop().animate({
            left: leftPos,
            width: newWidth,
            opacity: 1
        });
        console.log($magicLine.data("origLeft"));
    }, function () {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });
.mega-navigation--level-one {
    position: relative;
    list-style: none;
    padding: 0;
    margin: 0 auto;
    width:400px;
}
.mega-navigation--level-one > li {
  display:inline-block;
  margin: 0 10px;
}
.mega-navigation--level-one > li > a {
  color:#000; 
  font-weight:bold; 
  text-decoration:none;
}
.nav-hover {
  position: absolute;
  bottom: -12px;
  left: 0;
  width: 100px;
  height: 6px;
  background: #04aa84;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="mega-navigation--level-one">
<li>
<a href="#">Menu Item 1</a>
</li>
<li>
<a href="#">Menu Item 2</a>
</li>
<li>
<a href="#">Menu Item 3</a>
</li>
</ul>

Answer №1

It is recommended to increase the left property by 10px rather than 20px:

leftPos = $el.position().left + 10;

This is how your function should look:

$(".mega-navigation--level-one > li").hover(function () {
    $el = $(this);
    leftPos = $el.position().left + 10;
    newWidth = $el.width();

    $magicLine.stop().animate({
        left: leftPos,
        width: newWidth,
        opacity: 1
    });
    console.log($magicLine.data("origLeft"));
}

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 retrieve the value of an HTML variable using Selenium?

Seeking assistance in determining the progress value of a video using Selenium. I understand that I need to utilize JavaScript executor, but have been unsuccessful in finding a solution so far. The element in question is: <div aria-label="scrub bar" a ...

Proper way to effectively remove a previously attached handler in jQuery

One way to remove a previously added event handler is by using the following code snippet: var func = function() { $('body').append('<div>' + this.a + '</div>'); }, a1 = $.proxy(func, { a: 1 }); ...

What is the best way to align text to the left without causing it to wrap to the next line?

Currently, I am in the process of designing a banner that will only be displayed when necessary. I am looking for techniques to achieve this goal effectively. Is there a way to align text centrally only if it fits on one line and does not wrap onto a new ...

Random Exclamation Point Appears in Outcome of PHP HTML-Email

I have been encountering exclamation points appearing randomly in the output of my PHP email function. After some research, I learned that this could be due to long lines or the need to encode the email in Base64. However, I am unsure how to go about doing ...

Even after being removed, the input field in Firefox stubbornly maintains a red border

I have a project in progress that requires users to input data on a modal view and save it. The validation process highlights any errors with the following CSS snippet: .erroreEvidenziato { border: 1px solid red; } Here is the HTML code for the moda ...

Activate click events when button is being held down

I'm currently working on a directive that shifts an element to the right whenever clicked. However, I want the element to keep moving as long as the button is pressed. .directive("car", function(){ return { restrict:"A", link:func ...

Passing index value using navigateByUrl method

I have developed a home component and a view component to display different levels of employee details. The home component presents basic information, while the view component shows comprehensive details. The code in my home.component.html file looks like ...

Enhance the sent server parameters by including extra options in fineuploader

I have successfully implemented file uploads using . Everything works perfectly. I am able to set parameters in the request object to send additional data to the server. However, when I try to add another parameter dynamically using the setParams function ...

Vue app: ESLint throwing error for undefined global variable in component during npm run serve

In my main.js file, I am initializing a new Vue instance on the window object: window.todoEventBus = new Vue() Within my components, I am attempting to access this global todoEventBus object like so: created() { todoEventBus.$on('pluralise&apos ...

What is the best method for retrieving a local value in Javascript?

Consider a scenario where there exists a variable named animationComplete (which is part of a 3rd-party library) and a function called happenAfterAnimation: An easy solution would involve the following code snippet: while(!animationComplete) { // Do n ...

Eliminating memory leaks in a React web application

I'm facing an issue in my ReactJS web application with the following code: useEffect(() => { const fetchInfo = async () => { const res = await fetch(`${api}&page=${page}`); setLoading(true); try { const x = awa ...

What is the most efficient way to iterate through array elements within a div element sequentially using React?

Currently, I am working with a large array of 2D arrays that represent the steps of my backtracking algorithm for solving Sudoku. My goal is to display each step in a table format, similar to animations that illustrate how backtracking works. Although I ha ...

What is the best method for extracting and storing search suggestions data with selenium?

Initially, I had posted this inquiry before, and my apologies for reposting. However, I am still struggling to comprehend why the code works for the individual who responded but not for me. How can one retrieve values from search suggestions after enterin ...

Understanding the visibility scope in JavaScript's object-oriented programming

I have the following code snippet: function A() { this.AFunction = function() { var b = new B(); b.BFunction(); } } function B() { this.BFunction = function() { // some code $.ajax({ url: url suc ...

Dynamic hovering over isotopic elements

I'm looking to create a webpage where images are arranged dynamically like on this website: . I also want each image to have a hover effect displaying specific information about the image. After some research, I came across a JavaScript library calle ...

Is there a way to change the color of a number's font based on whether it is preceded by a "+" or "-" sign?

I am currently working on a stocks widget and I have a specific requirement. Whenever there is a change in value in the Change or Changeinpercent columns, I need to dynamically set the font color to red for a decrease (-) or green for an increase (+). Her ...

Unable to connect beyond the local network using Socket.io

server.js import { Server } from "socket.io"; const io = new Server(8000); io.on("connect", (socket) => { console.log(`connect ${socket.id}`); socket.on("ping", (cb) => { console.log("ping"); ...

Converting Uniquely Designed Photoshop Shapes into HTML

I am working on a project to design an HTML page that features a profile picture with a heart frame. I have the PSD file with the heart frame included. The profile pictures will be rectangular in shape and should fit behind the heart frame without overlap ...

`Is there a way to dynamically update a nested field object in Mongoose without updating the entire object?`

const userProfile = new Schema({ name: { type: String, default: null }, contacts: { mobileNumber: { countryCode: { type: String, default: null }, digits: { type: String, default: null } }, email: { type: String, default: null }, facebook: { ...

Leverage AngularJS to effectively parse JSON data using scope variables

I am trying to JSON parsing in AngularJS using $stateParams in the controller below: rerunApp.controller('rerunCategoryListCtrl', function($scope, $http, $stateParams) { var stpNameCat = $stateParams.nameCat; $http.get(JSON UR ...