What is the technique for utilizing JavaScript to toggle the opening and closing of a Bootstrap 5 navbar dropdown?

My website is built using Bootstrap 5, and I am working on creating a navbar dropdown functionality. On desktop, I want the dropdown to open on hover and lead to a new page when clicked. However, on mobile, I only want the dropdown to open and close on click without redirecting the user to a new page. Currently, my dropdown opens on hover and redirects to another page on desktop. On mobile, the dropdown opens on click but does not redirect, and there is an issue with closing the dropdown after opening it. I understand that this issue can be resolved with JavaScript, but I lack knowledge of JavaScript to fix it.

Desired Dropdown Functionality

Desktop/Laptop Dropdown Functionality

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

Mobile/Tablet Dropdown Functionality

  • Opens/closes on click
  • Does not redirect 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;
    }
}

@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" />
...
...
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
      </head>
      <body>
        
        <!-- NAVIGATION BAR START -->
        <nav class="navbar navbar-expand-lg navbar-light py-3 sticky-top" id="navbar-color">
          <div class="container">
            <a href="/index.html">
              <img src="./src/img/logo-topnav.png" height="45" width="225" class="img-fluid"/>
            </a>
...
...
            </script>
           
            </ul>
          </div>
          <!-- TOGGLE MENU CLOSE -->
          </div>
        
        </nav>
        <!-- NAVIGATION BAR CLOSE -->
    
      
      </body>
    </html>

Answer №1

To incorporate this script into your code, make sure to include the script file within the head tag prior to the closing of the body tag.

<script>
  // Detect if the device is touch-enabled
  let isTouch = false;
  document.addEventListener("touchstart", (event) => {
    isTouch = true;
  });

  // Locate the dropdown element
  let serviceNavElement = document.getElementById("nav_service_object");

  // Manage hover interactions on desktop
  serviceNavElement.addEventListener("mouseenter", function () {
    if (isTouch) {
      return;
    }
    serviceNavElement.href = "/Bootstrap-/services.html";
  });

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

  // Control click behaviors on mobile
  serviceNavElement.addEventListener("click", function (event) {
    if (isTouch) {
      event.preventDefault(); // Prevent the default link behavior
      let dropdownMenu = this.parentElement.querySelector(".dropdown-menu");
      if (dropdownMenu) {
        dropdownMenu.classList.toggle("show");
      }
    }
  });
</script>


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

The setState function in React updates the value, however, when a form is submitted, it captures and

Encountering a problem with a modified field value not remaining on the form after submission. Working on a form where users can upload images. The image URL returned by the hosting service is saved in a state variable using this.setState({ im ...

The getUserMedia() function fails to work properly when being loaded through an Ajax request

When the script navigator.getUserMedia() is executed through regular browser loading (not ajax), it works perfectly: <script> if(navigator.getUserMedia) { navigator.getUserMedia({audio: true}, startUserMedia, function(e) { __ ...

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...

Harnessing the Power of Google Apps Scripts: Mastering the Art of Handling Comma-Separated Spreadsheet Values Transformed

I have a spreadsheet where column 1 contains source file IDs, with each cell holding only one ID. Column 2 has destination file IDs, where cells contain multiple IDs separated by commas. I utilize a script to retrieve these values and perform various opera ...

Tips for implementing a switch-case statement with variable formats that may not always be

switch (req.path) { case "/api/posts": console.log("posts"); break; case "/api/posts/tags/*": // the part * is always changing depending on user input console.log("tags"); break; case "/api/best": console.log ...

"Learn how to trigger an event from a component loop up to the main parent in Angular 5

I have created the following code to loop through components and display their children: parent.component.ts tree = [ { id: 1, name: 'test 1' }, { id: 2, name: 'test 2', children: [ { ...

Converting a table into div elements and subsequently reverting it back to its original table format

[STOP DOWNVOTING: NEW AND IMPROVED] Discovering a simple technique on stackoverflow to transform tables into divs has been quite enlightening. By assigning classes to each tag, such as: <table class="table"> the process of converting from table to ...

Steer clear of dividing words

I am attempting to showcase sentences letter by letter with a fade in/fade out effect. However, I am facing an issue where words break in the middle. How can this word breaking be prevented? var quotes = document.getElementsByClassName('quote' ...

Create an onClick function that can direct you to a specific hyperlink without triggering a new browser window to open

Material UI is being used and a home icon has been imported into the navbar as shown below <Home edge="start" color="inherit" aria-label="home" onClick={event => window.location.href='/ <Home fontSize="lar ...

Placing the word "repeatedly" in a d3 js tree

I am currently working on building a tree structure and incorporating edge labels. The tree allows nodes to be dynamically added using a plus button that appears when you click on a parent node. One issue arises when adding a new child. (apologies for the ...

PhantomJS 2.0.0 not delaying page loading

In the script provided, there is an array of URLs called links. The function gatherLinks() is designed to collect additional URLs from the sitemap.xml file related to the ones in the links array. Once the number of URLs in the links array reaches a certain ...

An issue arose when attempting to proxy to: localhost, at port 4200, for the API endpoint v1/generate

Currently, I am following a tutorial which guides me through the process of creating an application using Angular CLI, Node.js, and Express. A proxy is used to initiate the app, with the proxy configuration file looking like this: { "/api/*": { ...

A New Approach to Initializing Web Pages in ASP.NET (with a Surprising Twist)

Well, I've encountered quite the puzzling issue with a project I'm working on (it could even make it to the Daily WTF), and I'm hoping for some help in finding a solution. (Apologies in advance for the lengthy explanation...) About a month ...

Exploring the Art of Programming SVG

I am thinking about creating a website that is similar to stackoverflow, but with the added feature of allowing answers to include drawings such as schematics. I would like to have a section in the answer form where users can create these schematics with ...

Support for Chrome in Angular 8

Can someone please advise on the minimum version of Google Chrome that is supported by Angular 8? Additionally, I am looking for a way to prompt users to update their Chrome browser if it doesn't meet the required version. My Angular application seems ...

Using Nestjs to inject providers into new instances of objects created using the "new" keyword

Is it possible to inject a provider into objects created by using the new keyword? For instance: @Injectable() export class SomeService { } export class SomeObject { @Inject() service: SomeService; } let obj = new SomeObject(); When I try this in my t ...

Guide on deleting files from WordPress Media Library directly using PHP in the frontend

I have searched various sources while creating my current code, but I have yet to find the answer to this question: Link 1 Link 2 Link 3 Link 4 Creating a file management system where admin access is restricted from WordPress. They will manage files th ...

What could be causing my getAsFile() method to return null?

Below is the code I have been working on: document.getElementById("Image_Panel").addEventListener('paste', (event) => { console.log("Initiating image paste - Step 1"); const clipboardData = event.clipboardData; // Checking ...

Encountering 404 Error in Production with NextJS Dynamic Routes

I'm currently working on a next.js project that includes a dynamic routes page. Rather than fetching projects, I simply import data from a local JSON file. While this setup works well during development, I encounter a 404 error for non-existent pages ...

Error arises on Github when submitting a pull request due to a conflicted package

When facing conflicts in the package.json file while submitting a pull request, what is the best approach to resolve them? I usually attempt using git pull origin, but it tends to generate numerous merge commits. ...