Utilizing JavaScript to enable a Bootstrap 5 dropdown menu to open on hover for desktop users and be clickable for mobile users

I am currently using Bootstrap 5 to design a website and I'm facing an issue with creating a navbar dropdown. On desktop, I want the dropdown to open on hover and redirect the user to a new page when clicked. However, on mobile devices, I only want the dropdown to be clickable for opening and closing without navigating to a different page. The current setup opens the dropdown on hover and leads to another page on desktop, but on mobile it's not clickable and redirects the user to another page. I understand that achieving this functionality requires JavaScript, which I am unfamiliar with. Can someone please assist me in implementing this?

Desired Dropdown Functionality

Desktop/Laptop Dropdown Functionality

  • Opens/closes on hover
  • Redirects to another page when clicked

Mobile/Tablet Dropdown Functionality

  • Open/closes by clicking
  • No redirection to another page

#navbar-color {
    background-color: hsl(210, 45%, 30%);
}

.navbar-light .navbar-toggler-icon {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 1%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
}

.navbar-light .navbar-toggler {
    border: 1px solid hsl(0, 0%, 100%);
    outline: none;
    box-shadow: none;
}

#nav_object {
    position: relative;
}


.dropdown:hover .dropdown-menu {
    display: block;
    background-color: hsl(210, 45%, 30%);
}

.dropdown-item:hover {
    background-color: hsl(210, 55%, 41%);
}

#nav_object {
    position: relative;
}

@media (min-width: 576px) {
    #nav_object::after {
        content: '';
        opacity: 0;
        transition: all 0.2s;
        height: 2px;
        width: 100%;
        background: hsl(18, 100%, 62%);
        position: absolute;
        bottom: 0;
        left: 0;
    }
    
    #nav_object:hover::after {
        opacity: 1;
    }
}

.dropdown-menu{
  --bs-dropdown-link-hover-bg: hsl(210, 55%, 41%) !important;
}

@media screen and (max-width: 576px) {
    .dropdown:hover > .dropdown-menu {
        display: block;
        margin-top: 0;
    }
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<title>Home | </title>

<link rel="stylesheet" href="/_bridgetown/static/css/main.c7d4dd3f1984a290e9be.css" />
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e4c41415a5d5a5c4f5e6e1b001d001e">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" 
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" 
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="./css/index.css" />
<link
          rel="stylesheet"
          data-purpose="Layout StyleSheet"
          title="Default"
    disabled
          href="/css/app-937c1ff7d52fd6f78dd9322599e2b5d4.css?vsn=d"
        >
        <link
          rel="stylesheet"
          data-purpose="Layout StyleSheet"
          title="Web Awesome"

          href="/css/app-wa-8d95b745961f6b33ab3aa1b98a45291a.css?vsn=d"
        >

          <link
            rel="stylesheet"

            href="https://site-assets.fontawesome.com/releases/v6.4.0/css/all.css"
          >

          <link
            rel="stylesheet"

            href="https://site-assets.fontawesome.com/releases/v6.4.0/css/sharp-solid.css"
          >

          <link
            rel="stylesheet"

            href="https://site-assets.fontawesome.com/releases/v6.4.0/css/sharp-regular.css"
          >

          <link
            rel="stylesheet"

            href="https://site-assets.fontawesome.com/releases/v6.4.0/css/sharp-light.css"
          >
        <link rel="icon" type="image/x-icon" href="/Bootstrap-/images/favicon-32x32.png">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfuniqo.udnoubecrumtelen"":""vPProuEqrdgctrdrfoootdarecepnoemDe>-pTlyten<">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>


  </body>
  <!-- NAVIGATION BAR START-->
<nav class="navbar navbar-expand-lg navbar-light py-3 sticky-top" id="navbar-color">
      <div class="container">
        <a href="/Bootstrap-/index.html">
          <img src="./src/img/logo-topnav.png" height="45" width="225" class="img-fluid"/>
        </a>

        <button
          type="button"
          class="navbar-toggler"
          data-bs-toggle="collapse"
          data-bs-target="#navmenu"
        >
          <span class="navbar-toggler-icon">
        </button>
       
      <div class="collapse navbar-collapse" id="navmenu">
        <ul class="navbar-nav ms-auto">
        <li class="nav-item"><a href="/Bootstrap-/index.html" class="nav-link text-white" id="nav_object">Home</a></li>
        <li class="nav-item"><a href="/Bootstrap-/about.html" class="nav-link text-white" id="nav_object">About</a></li>
             

        
        </ul>
      </div>
      
      </div>
    
    </nav>
    <!--NAVIGATION BAR CLOSE-->
 
 
  </body>
</html>

Answer №1

  1. Each of your navigation items should have a unique id, which I have updated for you.
  2. I've implemented a mouse event to meet your requirements - when the mouse enters the Service menu, the URL will be inserted, and it will be removed on mouse exit.
  3. If you're on mobile and tap on the Service item, it won't trigger the mouseenter event and won't redirect you to another page.
  4. If this solution works, you can apply the same technique to other navigation items as well.

let serviceNavElement = document.getElementById("nav_service_updated")
let isTouch = false
document.addEventListener("touchstart", (event) => {
  console.log("touch")
  isTouch = true
});

serviceNavElement.addEventListener("mouseenter",function(){
  if(isTouch){
    return
  }
  serviceNavElement.href = "/Bootstrap-/services.html"
  console.log(serviceNavElement)
})

serviceNavElement.addEventListener("mouseleave",function(){
  if(isTouch){
    return
  }
  serviceNavElement.href = "#"
  console.log(serviceNavElement)

})
#navbar-color {
    background-color: hsl(210, 45%, 30%);
}

.navbar-light .navbar-toggler-icon {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 1%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
}

.navbar-light .navbar-toggler {
    border: 1px solid hsl(0, 0%, 100%);
    outline: none;
    box-shadow: none;
}

#nav_object {
    position: relative;
}


.dropdown:hover .dropdown-menu {
    display: block;
    background-color: hsl(210, 45%, 30%);
}

.dropdown-item:hover {
    background-color: hsl(210, 55%, 41%);
}

#nav_object {
    position: relative;
}

@media (min-width: 576px) {
...

</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

What happens when tabs are dynamically added on keypress?

I am encountering issues with this code snippet. $('body').on("keypress", ".message", function(e) { if ( e.keyCode == 13 && $(".message").val().length > 0 ) { input = $(".message"); // Check for join com ...

How can I use querySelector in JavaScript to target all div elements that have the same class?

I'm having an issue with the document.querySelector in my JavaScript code. It currently only selects the first div that contains the class "test", but I need it to select all such divs. Is there a way to achieve this using my existing JavaScript? ...

The CSS border-radius feature shapes the corners without affecting the background

When I apply a 15px rounded border to a div, the border appears rounded on the outside but the corners where the border meets the background remain square. Here is an example: http://jsfiddle.net/BQT5F/1/ I tried using the background-clip property to add ...

Personalize the position of the v-select drop-down menu

I am currently working with the vuetify v-select component. The problem I am encountering is that instead of the dropdown opening downwards, I need it to open upwards since the dropdown is positioned at the bottom of the page which causes some of the dro ...

Detecting collisions in Three.js

I seem to be overlooking something quite fundamental, as I can't seem to find a solution in the documentation or any other working code examples. I am currently creating a basic museum using THREE.js libraries. While most of it is set up, I need to im ...

Searching for a column fails to yield any results after altering the value in

Here is a snippet of code that I am working with: <!DOCTYPE HTML> <html lang="en"> <head> <title> Exact matches overview </title> <script type="text/javascript" src="/static/s ...

An error occurred while trying to set the property 'IS_CHECK' of an object that is undefined

I'm attempting to create a checkbox that, when selected, should also select everything else. I followed the code example provided in this tutorial for angular 2. However, I encountered an error: "ERROR TypeError: Cannot set property 'IS_CHECK&ap ...

Safari (mac) experiencing issues with loading material icons properly on initial attempt

Upon my initial visit to the website, I noticed that the font appeared distorted. https://i.sstatic.net/BtUxI.png However, when I right-clicked and chose "reload page", the fonts were displayed correctly. https://i.sstatic.net/3XUcA.png This issue seem ...

Unique text: "Enhancing User Interaction: Using a custom directive to dynamically evaluate

Introduction: A simple demonstration of HTML structure: <td ng-repeat="col in cols"> <div ng-bind-html="col.safeHTML"></div> </td> JavaScript controller code snippet: $scope.cols = [ { field : 'logo&apos ...

The display of the AngularJS {{variable}} is not supported within a script tag

<script type="text/template"> <div class="abcd"> <div class="efg" data-price="{{::displayPrice}}"></div> </div> </script> I am facing an issue with a template that contains a div element with the da ...

Empty HTML fieldset

For a blog article I'm working on, I'd like to include a "Note" box that resembles a <fieldset> with a <legend> <fieldset> <legend>Note</legend> Please take note of this. </fieldset> (check out http:/ ...

Steps for Converting Unicode Characters to HTML Encoding in C++

Can you assist me with converting unicode characters like the ones below in C++? Thére Àre sôme spëcial charâcters ïn thìs têxt عربى I need to convert them to HTML encoding as shown below: Th&eacute;re &Agrave;re s&ocirc;me sp&am ...

I've been attempting to align the iframe element in the center without success, despite trying out various solutions from

Despite trying to center-align the div using style="text-align: center;", display: block, and align="center", none of these methods seemed to work for me. Here is the code including all attempts: <div align="center" style="text- ...

Creating a database using Angular2+ in CouchDB can be achieved by following these steps

I have been attempting to set up a database in couchdb using angular2+. My goal is to create a button that, when clicked, will initiate the creation of the database. However, I keep encountering an error message. "ERROR Error: Uncaught (in promise): H ...

How do I retrieve and pass values from multiple inputs in my React application?

I've implemented the <autocomplete> as an input field, and I'm currently troubleshooting my submit method by logging values to the console. Unfortunately, I can only submit empty data to my axios instance without any Traceback errors for gu ...

Verify whether the element in the DOM is a checkbox

What is the method to determine whether a specific DOM element is a checkbox? Situation: In a collection of dynamically assigned textboxes and checkboxes, I am unable to differentiate between them based on their type. ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

The element is not positioned correctly due to the absolute positioning

This is my first attempt at creating a jQuery plugin and I have almost got it working correctly. You can view the example here. I've been struggling for days to position an element as desired. The goal is to display some text with an optional downwar ...

Any tips for creating a website with non-redirecting tabs?

I'm currently working on a website project and I would like to incorporate tabs on the side of my site for easy navigation. I envision an interactive tab system where users can click on their desired category and be directed there instantly, rather th ...

How to insert an SVG into a <span> element using jQuery's find() method

I am encountering challenges when trying to select an svg element (originally written as img and later converted to svg using jQuery). Here is the code snippet: HTML: <div class="tab-content"> <div id="personas" class="active"> <s ...