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

Reset the child JSP page to its original appearance

Displayed below is a JSP page: <div id="tabs-7" style="width: 100%;"> <form:form id="deviceForm" name="" modelAttribute="" enctype="multipart/form-data"> <div class="inputWidgetContainer"> <div class="inputWidget"> <table> ...

"A validation error occurred in the ABC Ajax request in an Asp.net application due to invalid

Here is my script: <script type ="text/javascript"> $(document).ready(function () { $('#<%=Button1.ClientID %>').click(function () { var ABC = 'TEST'; $.ajax({ type: ...

Changing the Div heights in Material UI with grid layout customization

I have a project that requires me to implement material-ui. Is there a way I can adjust the width and height of the div containing the "Sign In With" text (as shown in the first image) to bring the buttons closer to the text? Transformation from this: ht ...

Changing from localhost:3000/admin to localhost:3000 within the local server

I am currently developing a node.js application. My goal is to have the homepage rendered after the admin successfully uploads data, transitioning from localhost:3000/admin to localhost:3000. I attempted to achieve this using the code snippet below: route ...

Tips for verifying if an object has been loaded prior to binding it with jQuery

When loading a "stub" file dynamically with jQuery that contains HTML objects, I aim to bind events to the loaded objects after they have finished loading. An example of what my external file may contain: <div id='myDiv'>click me</div& ...

The 'SVGResize' or 'onresize' property is not available on the 'SVGProps<SVGSVGElement>' type

Using React with SVG I'm facing an issue with handling the resizing event of an svg element. I have looked into using the SVGResize and onresize events, but encountered compilation errors when trying to implement them: const msg1 = (e: any) => co ...

What is the best way to determine if any of the list items (li's) have been marked as selected?

<div id='identifier'> <ul id='list'> <li id='1' class="">a</li> <li id='2' class="">a</li> <li id='3' class="">a</li> <li id='4' class=" ...

Converting an object to JSON in javascript: A step-by-step guide

I have been attempting to convert my object person into a JSON format. const person = new Object(); person.firstName = 'testFirstName'; person.lastName = 'testLastName'; var myJson = JSON.stringify(person); ...

The TypeScript error reads: "An element is implicitly assigned the 'any' type because an expression of type 'any' cannot be used to index a specific type."

[Hey there!][1] Encountering this TypeScript error message: { "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ 0: { image: string; title: string; text: string; }; 1: { ...

Load options from server directory using PHP jQuery AJAX

I am faced with a file structure on my server that resembles the following: My query is quite complex: How can I dynamically populate <select> HTML tags from the contents of sub-files on a server? For instance, I have 3 <select> tags here tha ...

Adding clickable padding to a Draft.js editor can enhance the user experience and make the editing process

Is there a way to apply padding to the Draft.js Editor so that clicking on the padding area selects the Editor? If I add padding directly to the container div of the Editor, the padding displays properly but clicking on it does not enable writing in the E ...

Tips for submitting a form using javascript while preventing the default action

Looking for a way to submit a form in Javascript and prevent the default action? Let's explore how you can achieve this. Initially, my HTML form with the ID "contact_form" had an input element like so: <input id="contact_send_msg" type="submit" val ...

How can one determine if a new document was created by Mongoose's upsert feature?

My code in node.js/express.js looks like this: var User = mongoose.model('User'); var usersRouter = express.Router(); usersRouter.put('/:id', function(req, res) { req.body._id = req.params.id; var usr = new User(req.body); ...

Combining two elements in Angular 2

I am looking to find the intersection of two objects. My goal is to compare these objects and if they have matching values on corresponding keys, then I want to add them to a new object. obj1 = { "Projects": [ "test" ], "Companies": [ "facebook", "google ...

Unexpected triggering of second fail in Jquery Deferreds

Currently, I have a sequencing function that involves two REST steps - step 1 and step 2. The way I am currently handling this is by calling step1 with fail and then handlers, followed by step2 with its own fail and then handler. self.step1() .fail(se ...

Using JavaScript with namespaces in C#

I am currently trying to explore AJAX and web services through self-teaching using C# and JavaScript. After doing some research on Google, it seems like I might be facing a namespace problem. Here is the snippet of my code: using System; using System.Col ...

MariaDB won't generate JSON output for a column that has a JSON data type

Currently, I am utilizing MariaDB and phpMyAdmin to effectively manage my database. Within one of my tables, I have a specific field that is defined as type json, or alternatively longtext. However, whenever I execute a SELECT query using JSON_EXTRACT(fiel ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

using laravel to make ajax requests with dynamic parameters

I'm facing an issue with an ajax call. The specific url I am trying to retrieve data from is: localhost/public/getCode?course_id=1&task_id=1 This is the ajax call I have set up: function getCode() { $.ajax({ ...

Code written in Javascript runs before any CSS files are downloaded and processed

While researching async scripting in web applications, I stumbled upon an interesting article. Essentially, it suggests that JavaScript scripts are not executed until all stylesheet CSS files are downloaded and parsed. Intrigued by this concept, I decided ...