Changing the sliding underline effect in a jQuery navigation bar

Recently, I implemented a sliding underline element in my navigation bar. The idea is that when a link is hovered over, the underline smoothly transitions to that element. You can take a look at the codepen example here: https://codepen.io/lucasengnz/pen/eQaQxy

However, I'm facing an issue where I want the underline to slide back to the first link when the navigation isn't being used. As someone who is new to utilizing javascript and jQuery, I am unsure how to tackle this problem. Any advice or pointers would be greatly appreciated.

$(".underline-nav").css("width", $("#one").width());
$(".underline-nav").css("margin-left", $("#one").css("margin-left"));

$('nav a').hover(function() {
  $(".underline-nav").css("width", $(this).width());
  $(".underline-nav").css("margin-left", $(this).css("margin-left"));
  var position = $(this).position();
  $(".underline-nav").css("left", position.left);
})
.underline-nav {
  background: tomato;
  height: .25rem;
  position: absolute;
  top: 1.8em;
  transition: all ease 0.3s;
}

nav {
  font-size: 1.85em;
}

nav a {
  text-decoration: none;
  color: #000;
  float: left;
  margin-top: 1vh;
}

#one {
  margin-left: 2vw;
}

.floatright {
  float: right;
  padding-right: 3vw;
}

.floatright a {
  margin-left: 4vw;
}
<div class="container">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <nav>
    <a id="one" href="#">one</a>
    <div class="floatright">
      <a id="tt" href="#">two</a>
      <a href="#">three</a>
      <a href="#">four</a>
      <a href="#">five</a>
    </div>
    <div class="underline-nav">
    </div>
  </nav>
</div>

Thank you for any assistance provided.

Answer №1

If you want to achieve this effect, follow these steps:

    $(".underline-nav").css("width", $("#one").width());
    $(".underline-nav").css("margin-left", $("#one").css("margin-left"));
    var unav = $(".underline-nav");
    $('nav a').mouseover(function(){
        var position = $(this).position();
        unav.css({
          "width": $(this).width(),
          "margin-left": $(this).css("margin-left"),
          "left": position.left
        });
    })
    $('nav').mouseleave(function() {
      var firstChild = $(this).find('a:first-child');
      var position = firstChild.position();
        unav.css({
          "width": firstChild.width(),
          "margin-left": firstChild.css("margin-left"),
          "left": position.left
        });
    })

Answer №2

.hover Attach one or two functions to the selected elements, which will be triggered when the mouse cursor enters and exits those elements.

This allows you to add an underline effect to the first element when the mouse pointer moves away from it.

$(".underline-nav").css("width", $("#one").width());
$(".underline-nav").css("margin-left", $("#one").css("margin-left"));

$('nav a').hover(function() {
  $(".underline-nav").css("width", $(this).width());
  $(".underline-nav").css("margin-left", $(this).css("margin-left"));
  var position = $(this).position();
  $(".underline-nav").css("left", position.left);
},
function () {
  // revert to initial state on mouse leave
  $(".underline-nav").css("width", $("#one").width());
  $(".underline-nav").css("margin-left", $("#one").css("margin-left"));
  $(".underline-nav").css("left", $("#one").position().left);
}
)
.underline-nav {
  background: tomato;
  height: .25rem;
  position: absolute;
  top: 1.8em;
  transition: all ease 0.3s;
}

nav {
  font-size: 1.85em;
}

nav a {
  text-decoration: none;
  color: #000;
  float: left;
  margin-top: 1vh;
}

#one {
  margin-left: 2vw;
}

.floatright {
  float: right;
  padding-right: 3vw;
}

.floatright a {
  margin-left: 4vw;
}
<div class="container">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <nav>
    <a id="one" href="#">one</a>
    <div class="floatright">
      <a id="tt" href="#">two</a>
      <a href="#">three</a>
      <a href="#">four</a>
      <a href="#">five</a>
    </div>
    <div class="underline-nav">
    </div>
  </nav>
</div>

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 the JSON parsing issue being caused by Bodyparser?

I am encountering an issue with parsing JSON on my server using the body-parser NPM module and Express. The JSON data is not appearing correctly on the server for some reason. Here is a snippet of my server code: ... app.use(bodyParser.json()); app.use(bo ...

Obtain an array of responses using jQuery ajax and pass it to PHP

I'm working on a project where I need to populate a table from MySQL based on a selection made in a select box using jQuery AJAX. Currently, this is the jQuery code that I have written. I am able to display the result in an alert box, but I am uncerta ...

CloudFront for Amazon - Limit MP3 playback to designated website

I've been trying to find a solution for allowing mp3 files in an Amazon S3 bucket paired with Cloudfront to be streamed directly on my site without revealing the source URL of the mp3s. I want to prevent others from sharing or leeching the link by vie ...

Passing form data to PHP using AJAX in CodeIgniter Framework

I'm facing an issue with my HTML structure which is as follows: <form method="POST"> Name : <input id="asgname" type="text"> <br> Description : <input id="asgdescription" type="text"> <br> <a href="#" id=" ...

The jQuery event handler fails to activate on the initial page load, however, it functions properly after refreshing the page and inspecting the DOM

Encountering a challenge with IE9 and jQuery. Click events on anchor tags function in Chrome, Firefox, and Opera, but fail to fire or have unexpected behavior in IE9. This issue only occurs upon the initial page load when the cache is empty. When clicking ...

HTML Multi-Column List Box

Can a List Box be created with List Items displayed in Multiple Columns? I know there are other options available, but I'm curious if this is achievable using the <select> tag ...

Create a new NVD3 graph with a vertical line added

I am working with a NVD3 graph that displays a simple data set. My goal is to draw a line over the graph in a different color (similar to a cut-off value, which will be at x=5) <meta http-equiv="content-type" content="text/html; charset=UTF8"> <s ...

Transform JSON data into HTML format while excluding particular values

I recently integrated a JSON API that fetches event data. Here's a snippet of the JSON structure: { "id":1, "status":"ok", "start":{ "date":"2021-01-16" } } To display this ...

What is causing this unique component to be positioned outside of the <tr> tag?

table.vue ... <tbody class="table-body"> <slot></slot> </tbody> ... TableCellRow.vue <template> <td class="table-row-cell" :class="this.class"> <s ...

Can one extract a property from an object and assign it to a property on the constructor?

Currently working with TypeScript, I am looking to destructure properties from an object. The challenge lies in the fact that I need to assign it to a property on the constructor of the class: var someData = [{title: 'some title', desc: 'so ...

The second attempt at an AJAX call is unsuccessful

I am currently developing a form that displays database results based on two entries: Automarke (brand) and Modell (model). You can view the entries here. The Modell dropdown dynamically changes based on the selected Automarke. Here is the code snippet I ...

Add a parameter to the iframe that is dynamically loaded into the DOM after a user clicks on

I am attempting to automatically play a YouTube video within an iframe. The iframe is only loaded into the DOM when I activate a trigger element: a.colorbox.cboxElement How can I add the parameter ?autoplay=1 to the end of the iframe URL upon click, consi ...

handle an exception within the initializer of its object

I'm currently working with an Ajax object that is utilized in various other objects to load 'Json' files. One issue I'm facing is trying to catch the 404 'Not found' exception thrown in the initializer object. However, every ...

Transforming a Nestjs string object into JSON data

I need to convert this to JSON format. I attempted to use JSON.parse(), but encountered an error. "{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Ut ...

The presence of floats in CSS influence the surrounding div elements

Currently experimenting with HTML/CSS utilizing Bootstrap v5.0 and encountering issues with the unusual interactions between floats and divs. Specifically, aiming to achieve the following: https://i.sstatic.net/4lpC2.png Successfully achieved the desired ...

A comprehensive tool for testing JavaScript, CSS, HTML, and jQuery code

Currently, I am working on an extension for Google Chrome that consists of multiple .js, .css, and .html files. My coding process involves using Notepad++ as my primary tool. However, I find myself needing to conduct testing at various stages of developm ...

Techniques for verifying phone numbers from various countries

The number of digits in a mobile number differs from country to country. I have tried using regular expressions, however, for example, India allows 10 digits, but this does not validate UAE, where the number of digits can range from 7 to 9. ...

Utilize React to iterate through a dictionary and display each entry

Essentially, I am pulling data from my API and the structure of the data is as follows: { "comments": [ { "user": "user1" "text": "this is a sample text1" }, { "user": "user2" "text": "This is a simple text2" }, } ...

Changing the value of an object property (illustrated using a basic linked list)

I am working on a JavaScript Link List implementation as a beginner, and I have written the following code: var LinkList = function () { this.LinkedList = { "Head": {} }; }; LinkList.prototype = { insert: function (element) { var Node = this ...

When navigating a website, how can one prompt a popup window to appear with a form that, upon submission, will directly update a select element on the original page?

Apologies, but I am struggling to phrase this question more clearly. This is the main focus of my page: When I choose the "New Element" option from the drop-down menu, a popup window (or any other designated element) should appear: Once the form is fill ...