Using jQuery to create dynamic CSS effects directly on the drop-down menu button

Seeking your kind assistance once again...

I am attempting to design a navigation bar that

  • displays the dropdown section upon hovering over the buttons AND
  • shows a bottom border on the button that was last hovered over

My code functions properly when I move my mouse

  • from menu button --> dropdown area --> outside or
  • from menu button --> menu button

However, the issue arises when I move my cursor

  • from menu button --> outside (i.e. left or right of the buttons, not below)

In this case, I wish for the border style to disappear but it remains visible.

Below is the code snippet.

$(document).ready(function(){
  var count = 0;
  $("#menu1,#menu2,.topnav-dropdown").mouseenter(function(){
    count++;
    $(".topnav-dropdown").css({"height": "6em","transition-duration":"0.1s"});
    if($(this).is("#menu1,#menu2")){
      $(".menuitem").children().css({"border-bottom":"none"});
      $(this).children().css({"border-bottom":"0.2em solid #111"});
    }
  })
  $("#menu1,#menu2,.topnav-dropdown").mouseleave(function(){
    count--;
    if (!count){
      $(".topnav-dropdown").css({"height": "0","transition-duration":"0.2s"});
      if($(this).is(".topnav-dropdown")){
        $(".menuitem").children().css({"border-bottom":"none"});
      }
    }
  });
});
* {
  box-sizing: border-box;
  margin: 0;
  font-size: 100%;
}

.clearfix {
  clear: both;
}

.top-section {
  height: 2em;
}

.topnav {
  width: 70%;
  margin: auto;
}

.menuitem {
  float:left;
  margin: -0.1em;
  height: 3em;
  display: flex;
  align-items: center;
  overflow:hidden;
  padding-top: 1em;
}

.menuitem-a {
  font-size: 1em;
  margin: 0 1em 0;
  text-decoration: none;
  color: black;
  height: 100%;
}

.menuitem-a:visited {
  color: black;
}

.topnav-dropdown {
  position: absolute;
  top: 2.9em;
  width: 100%;
  background-color: #333;
  z-index: 1;
  height: 0;
}
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <div class="top-section">
    <div class="topnav">
      <div id="menu1" class="menuitem">
        <a class="menuitem-a" href="#">Menu1</a>
      </div>
      <div id="menu2" class="menuitem">
        <a class="menuitem-a" href="#">Menu2</a>
      </div>
    </div>
    <div class="clearfix"></div>
    <div class="topnav-dropdown">
    </div>
  </div>
</body>
</html>

I attempted modifying the second last line of jQuery:

if($(this).is(".topnav-dropdown"))

to

if($(this).is("#menu1,#menu2,.topnav-dropdown"))

however, this also eliminates the border when transitioning from the button to the dropdown area..

Your assistance in this matter would be highly appreciated!

Answer №1

This task is more challenging than it may seem at first glance. I believe I have addressed all the key points.

$(document).ready(function() {

  $("#menu1").mouseenter(function() {
    $("#menu2").children().css({
      "border-bottom": "none"
    });
    $(this).children().css({
      "border-bottom": "0.2em solid #111"
    });
    $(".topnav-dropdown").css({
      "height": "6em",
      "transition-duration": "0.1s"
    });
  });

  $("#menu2").mouseenter(function() {
    $("#menu1").children().css({
      "border-bottom": "none"
    });
    $(this).children().css({
      "border-bottom": "0.2em solid #111"
    });
    $(".topnav-dropdown").css({
      "height": "6em",
      "transition-duration": "0.1s"
    });
  });

  $("#menu1, #menu2").mouseleave(function() {
    if (!$(".topnav-dropdown").is(":hover")) {
      $(".menuitem").children().css({
        "border-bottom": "none"
      });
      $(".topnav-dropdown").css({
        "height": "0",
        "transition-duration": "0.2s"
      });
    }
  });

  $(".topnav-dropdown").mouseleave(function() {
    $(".menuitem").children().css({
      "border-bottom": "none"
    });
    $(this).css({
      "height": "0",
      "transition-duration": "0.2s"
    });
  });

});
* {
  box-sizing: border-box;
  margin: 0;
  font-size: 100%;
}

.clearfix {
  clear: both;
}

.top-section {
  height: 2em;
}

.topnav {
  width: 70%;
  margin: auto;
}

.menuitem {
  float: left;
  margin: -0.1em;
  height: 3em;
  display: flex;
  align-items: center;
  overflow: hidden;
  padding-top: 1em;
}

.menuitem-a {
  font-size: 1em;
  margin: 0 1em 0;
  text-decoration: none;
  color: black;
  height: 100%;
}

.menuitem-a:visited {
  color: black;
}

.topnav-dropdown {
  position: absolute;
  top: 2.9em;
  width: 100%;
  background-color: #333;
  z-index: 1;
  height: 0;
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <input type="hidden" id="hid">
  <div class="top-section">
    <div class="topnav">
      <div id="menu1" class="menuitem">
        <a class="menuitem-a" href="#">Menu1</a>
      </div>
      <div id="menu2" class="menuitem">
        <a class="menuitem-a" href="#">Menu2</a>
      </div>
    </div>
    <div class="clearfix"></div>
    <div class="topnav-dropdown">
    </div>
  </div>
</body>

</html>

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

Consolidate HTML project into a unified HTML file

In my current project, I am working with a static HTML report that is organized in the structure outlined below: 1.css 2.font 3.js 4.pages 5.attachments 6.index.html I would like to know how I can combine all these elements to create a unified 'repor ...

Combining Versioning with BundleConfig.cs: A Comprehensive Guide

Encountering a recurring issue where changes made to CSS or Javascript files do not reflect in client browsers unless they manually refresh the page with ctrl+F5. This poses a challenge, especially in a school system with numerous users who may not be awar ...

Form submission issue persists despite ajax partial rendering

Currently, I'm working on a website that allows users to express their wishes. My goal is to make it as user-friendly as possible by allowing them to create wishes from any page on the site. To achieve this, I am considering using a jQuery/Ajax approa ...

What are some creative ways to incorporate images into SVG paths?

Check out my JSFiddle here. I'm attempting to position this image in the center of my arc. My initial thought was to use .attr("fill","url('somePicture')"), but so far, no luck with that approach. const width = 700; const height = 600; con ...

JQuery: Issue with closing modal on certain popups

I have configured a popup that is associated with 6 different products. While it functions correctly for the first product, it does not seem to work properly for the rest. <script> //var modal = document.getElementById("m ...

How can I improve the empty space in HTML after PHP processing?

Here are the lines displayed in HTML: <a href='http://www.1stheme.dev/?frontiles=1946'> <article class="post-1946 frontiles type-frontiles status-publish hentry Width_1_Height_1 " style="width:326px;height:326px;text-align:left;" id="po ...

Validation of custom fields for shipping carriers on the checkout page of a WooComerce store

I have successfully customized the shipping method section by adding two custom input fields and making them conditionally required. These fields only appear and become mandatory when a specific radio button is checked, thanks to my jQuery code that handle ...

Proceed to the following part - JQuery

I am currently working on a horizontal layout and trying to use jQuery to navigate to different HTML sections when an anchor is clicked. My goal is to jump to the next section upon clicking. While I have seen examples of this being done vertically, I am s ...

Share identification but display the label

I'm currently utilizing the jQuery plugin Tag-It for managing auto-suggestion and tagging functionalities. The data retrieval through an Ajax call is operating smoothly. Right now, the data is being fetched in the following format: {"itemID":"ItemNa ...

Transform the styles from a React component into Cascading Style Sheets

I have been tasked with transitioning all the styles from the JavaScript file to the CSS file while ensuring the design remains intact. I am facing an issue where using the CSS styles breaks the search field design. The original design can be seen here: S ...

Combine the values in the rows over a period of time

I have a set of three times in the format of Minute:Seconds:Milliseconds that I need to add together to get the total time. For example, let's say I have: 0:31.110 + 0:50.490 + 0:32.797, which equals 1:54.397. So how can I achieve this using JavaScr ...

Elements that allow for asynchronous data submission without requiring a traditional submit button

Hey there, I could really use some help with this puzzle I'm trying to solve. Here's the situation: <ul> <li>Number: <span id="Number">123</span></li> </ul> I want to set up a connection between t ...

Customize the appearance of radio buttons with unique colored outer and inner circles

I am in need of creating a MUI radio button that features a unique outer ring color compared to the selected inner fill color. Although I have reviewed the official documentation, it appears that customization options only allow for changing the color as ...

Oops! An error has occurred: The requested method 'val' cannot be called on an undefined object

I am struggling with this issue. This is the code that I am currently working on: http://jsfiddle.net/arunpjohny/Jfdbz/ $(function () { var lastQuery = null, lastResult = null, // new! autocomplete, processLocation = function ...

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...

transfer jquery element using jquery ajax

How can I send a jQuery object to a PHP function using POST? When I stringify the object, I get the following output: [ { "id": "701", "user_id": "2", "playlist": "ukg%20garage", "tracks": "5", "thumbnail": "Coldplay.jpeg", "crea ...

Ways to showcase information from an angular service

I'm struggling with displaying data from a service in my HTML view using AngularJS. My goal is to show a list of submitted forms called Occurrences in the view. When clicking on a list item, I want to be able to view all the data fields submitted thro ...

How do I troubleshoot and resolve this problem with jQuery and Ajax?

I have 4 text inputs that look like this: <input type="text" name="amount" id="amount"> <input type="text" name="commission" id="commission"> <input type="text" name="discount" id="discount"> <input type="text" name="total_amount" id ...

The clash between two jQuery plugins featuring identical function names

I have encountered a dilemma while working on a large website that includes two conflicting jQuery plugins for autocomplete functionality. The first plugin is jquery.autocomplete.js (not part of jQuery UI) which defines the autocomplete function like this ...

Some of the Tailwind CSS colors may not be fully supported by Next.js for rendering

Don't forget to showcase all the amazing Tailwind CSS Colors, Sometimes they go missing unexpectedly, and only a few decide to make an appearance. I try to add them manually one by one, but sometimes they just don't show up on the map. Edit: ...