The positioning of the <a> tag seems to be slightly skewed

My goal was to add a simple dotted underline animation to the menu bar on my website, so I crafted the following HTML:

<nav role="navigation" class="navigation">

  <ul class="nav-listed-links">
    <li class="active"><a href="">Home</a></li>
    <li><a href="">About</a></li>
    <li><a href="">Our Potfolio</a></li>
    <li><a href="">History</a></li>
    <li><a href="">Contact US</a></li>
    <li class="underline"></li>
  </ul>

</nav>

Additionally, I created this JS code to animate the moving underline.

JS:

$('.nav-listed-links > li > a').hover(function() {

  var offset = ($(this).offset().left - 0),
    width = $(this).outerWidth();

  $('.underline').addClass('on');

  $('.underline').css({
    left: offset,
    width: width
  });

}, function() {

  $('.underline').removeClass('on');


});

The smooth animation is achieved using CSS transitions, FIDDLE HERE.

Despite my efforts, I encountered an issue with the position of the underline not aligning with the start of the <a> tag, as shown in the screenshot below:

https://i.sstatic.net/6aoFu.jpg

I am puzzled by this discrepancy and haven't yet been able to determine the cause. Any insights or suggestions would be greatly appreciated.

Answer №1

Utilizing the offset() function enables you

to retrieve the current position relative to the document

Thus, due to the default margin of the body, an additional gap is created.

To prevent any issues, I recommend utilizing the position() function, as it ensures that the underline is in relation to the ul container:

retrieve the current position of an element relative to the offset parent

var offset = $(this).position().left,

Check out the Updated Fiddle


Reference Position() Documentation

Answer №2

The issue at hand is primarily caused by the margin applied to the body in the current setup. To resolve this, simply setting margin: 0 will produce the desired outcome. It's possible that similar margins are present on other surrounding elements, so those should be adjusted accordingly as well.

To see the solution in action, check out the updated JSFiddle with margin-left: 0px; specifically added to the body element here: https://jsfiddle.net/w8unr0od/2/

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

Identifying CSS when the height of the browser is smaller than the height of the device

On my page, I am facing a situation where the CSS of an element needs to be adjusted for devices like the Nexus 5X. These devices have 'Android nav bars' at the top and bottom, which can push elements around on the page. Currently, I am using jQ ...

problems with my ajax or jquery in codeigniter

Hey guys, I have successfully implemented the image edit update feature. However, I am facing an issue with the ajax call when I try to delete an image by clicking on the edit button. It gives me an error that I can't seem to figure out. Can anyone he ...

Having trouble retrieving the property from the object that was returned

I'm facing a challenge where I'm unable to properly query the JSON response I receive. However, I can successfully print out the entire response using a msgBox() prompt. Here's an excerpt of the JSON response that I managed to see through th ...

The OBJMTLLoader disregarded the MTL file

After downloading a free model from Turbosquid, I found that it included an obj and mtl file along with textures like specular and bump maps. Focusing only on the mtl and obj files, I decided to use a car model from this link (http://www.turbosquid.com/Ful ...

When using $.getJSON and $.ajax, the expected JSON object is not being returned

Currently, I am taking on the "local weather" front-end development challenge on freecodecamp.com. However, I'm facing some challenges when it comes to making an API call to fetch weather data from various weather APIs. This particular task requires r ...

The transparency of the text in my navbar is glitching when I scroll down

I'm experiencing an issue with my navbar text becoming translucent when scrolling. How can I fix this problem? Check out the picture below for more details. ...

What is the best location to put initialization code in Firebase cloud functions?

We have decided to implement the express-ajv-swagger-validation middleware for validating our api requests. I noticed that it has an async function for initialization and I am curious about how to properly initialize it with the swagger json file. If it ...

JavaScript issue causing input fields to malfunction and clear text boxes

I apologize for the simplicity of this question, but I am struggling with an issue and seeking help. Here's the problem: my calculate() method is not clearing text input as expected when testing my page. Below is the HTML markup and script: <!DOC ...

How can jQuery each() be combined with casperjs?

I'm struggling to echo the ids of elements that match my selector because I'm confused about two different uses of 'this'. When I want to echo something in CasperJS, I use this.echo(). However, when I'm using .each(), 'this&a ...

The :first selector examines the parent's parent as a reference point, rather than the immediate

I am facing a challenge with shuffling large elements within my layout because of floating them and attempting to display them. Specifically, the elements with the class .gallery-large always need to be the first child inside the .item container. There are ...

Utilize local storage to dynamically update the background color of a div section

Struggling to create a functionality on my website where users can input a color, save it to localStorage, and have a specific div's background set to that color across all pages. The main content div (with the same ID) needs to display this color con ...

How can I assign a class to my Typography component in Material UI?

When using my material-ui component, I wanted to add an ellipsis to my Typography element when it overflows. To achieve this, I defined the following styles: const customStyles = (theme) => ({ root: { textAlign: "left", margin: theme.spacing( ...

Strategies for positioning a fixed div at the bottom of another div

I'm in the process of creating a digital restaurant menu... I decided to format it as a popup, situated within a fixed container on top of a gray transparent overlay. However, with a large number of dishes, the content exceeds the size of the containe ...

Modifying the initial state values in Redux Form is prohibited

I'm facing an issue with my redux-form component. I have successfully passed the initial form state values, but when I try to edit them by clicking inside the form, nothing happens. I've diligently followed all the documentation available, includ ...

What are the steps to restrict a user from accessing a specific website?

In my Vue.js project, I've implemented a function that hides a specific menu item for users with insufficient permissions: <a :href="href" @click="navigate" v-if="hideMenuItem()"> // some code </a> hideMe ...

Automatically calculate the quantity of pie charts to showcase and present each one individually on a CanvasJS-generated page

I am looking to create multiple pie charts dynamically and display them together on a webpage. The number of pie charts needed will be determined by the elements in a JSON object. Here is an example of how the data will be structured: [ { "id" : "12 ...

Is there a way to send the image's name as a parameter?

I am facing a challenge in achieving a specific task and need some guidance. My current approach involves passing the image name as a parameter to the cancelimage.php script, but it seems like I am not utilizing the variable 'image_file_name' cor ...

Tips for avoiding Client DOM XSS vulnerability in JavaScript

Upon completing a checkmarx scan on my code, I received the following message: The method executed at line 23 of ...\action\searchFun.js collects user input for a form element. This input then passes through the code without proper sanitization ...

Having trouble drawing over buttons in HTML5 Canvas?

window.addEventListener("load", () => { const canvas = document.querySelector("#canvas"); const ctx = canvas.getContext("2d"); const color = document.querySelector("#color"); const strokeWeight = document.querySelector("#strokeWeight"); ...

Converting Markdown files to HTML with the help of marked.js

While working on my project, I encountered the need to render a markdown file (.md) within a <body> component of an HTML page. After some research, I discovered marked.js. The documentation outlines a method for achieving this: marked.parse('# ...