Navigating on a page using anchor tags within a dropdown menu

I'm in the process of creating a top navigation bar with dropdown functionality that appears when hovering over certain navigation items. Here's how it currently looks:

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();   
  });
  
    const $dropdown = $(".dropdown");
    const $dropdownToggle = $(".dropdown-toggle");
    const $dropdownMenu = $(".dropdown-menu");
    const showClass = "show";
  
    $(window).on("load resize", function() {
      if (this.matchMedia("(min-width: 768px)").matches) {
        $dropdown.hover(
          function() {
            const $this = $(this);
            $this.addClass(showClass);
            $this.find($dropdownToggle).attr("aria-expanded", "true");
            $this.find($dropdownMenu).addClass(showClass);
          },
          function() {
            const $this = $(this);
            $this.removeClass(showClass);
            $this.find($dropdownToggle).attr("aria-expanded", "false");
            $this.find($dropdownMenu).removeClass(showClass);
          }
        );
      } else {
        $dropdown.off("mouseenter mouseleave");
      }
    });
  
  
.navbar{
  background-color: black;
  padding-left: 5vw;
  padding-right: 4vw;
}

.navbar .nav-item{
  text-align: center;
  padding-top: 40px;
  padding-bottom: 40px;
}

.navbar .nav-item .nav-link{
  color: white;
  font-size: 18px;
  font-family: 'Roboto';
  font-weight: bold;
}

.navbar .nav-item .nav-link:hover{
  color: red;
  text-decoration: none;
}

.navbar .nav-item a:hover{
  color: #4c4c4c;
}

.navbar .nav-item:not(:last-child) {
  margin-right: 5px;
}

.dropdown-toggle::after {
   transition: transform 0.15s linear; 
   content: none;
}

.show.dropdown .dropdown-toggle::after {
  transform: translateY(3px);
}

.dropdown-menu {
  margin-top: 5px;
  border-top: 5px solid red;
  border-radius: 0;
  padding: 0;
}

.navbar .nav-item a{
  font-size: 18px;
  color: #080808;
  padding-top: 12px;
  padding-bottom: 12px;
  padding-right: 40px;
  font-weight: 400;
  font-family: 'Roboto';
  background-color: none;
  border-bottom: 1px solid rgba(193,193,193,0.59);
}

.navbar .nav-item .nav-link{
  border-bottom: none;
}
<nav class="navbar navbar-expand-lg">
    <div class="container-fluid">
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item dropdown">

                    <a href="#information" class="nav-link dropdown-toggle" id="navbarDropdown1" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        About Us
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown1">
                        <a class="dropdown-item" href="#">Who we are</a>
                        <a class="dropdown-item" href="#">What we do</a>
                    </div>
                </li>

                <li class="nav-item">
                    <a class="nav-link" href="#">Events</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Contact Us</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

My objective is to have both dropdowns appear on hover and have the navigation functionality working, where clicking on a dropdown item will navigate the user to a specified section. In the current code, "About Us" should show its dropdown on hover and navigate to the specified section ("#information") when clicked.

Unfortunately, I'm only able to get one of these functionalities working at a time. If the dropdown works on hover, the navigation doesn't, and vice versa.

Any assistance would be greatly appreciated.

Thank you.

Answer №1

On mobile devices, the lack of hover functionality prevents the submenu from opening with a click to navigate to the desired section. This can be problematic, but Bootstrap has a solution for this scenario.

If you want to ensure the submenu works on mobile, it's recommended to maintain the anchor navigation and include the following code snippet:

$("#navbarDropdown1").click(function() {
  if ($(window).width() > 991) {
    var href = $(this).attr('href');
    $('body, html').animate({ 
      scrollTop: $(href).offset().top
    }, 600);
  }
});

This code allows the "About Us" section to be navigated to with a click, but only if the screen width exceeds the Bootstrap breakpoint for mobile devices (991px).

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

Tips for positioning your datepicker to align to the left

Can anyone please help me? I am struggling with positioning the datepicker on Bootstrap. I want it to be aligned to the left but it's not working as expected. Can someone please assist me in improving the logic below? Also, I need help in changing the ...

Incorporating a flexible header size and scrollable content: Tips for avoiding the need to scroll through the entire page to find

I am currently working on creating a unique page template that has certain requirements: The height of the header may vary The content and aside containers should be independently scrollable Anchor links should not disrupt the page layout To see what I h ...

The Modal Textarea refreshes each time it is clicked

Whenever I try to type on the modal with 2 textareas, it stops and exits the textarea. The issue seems to be with onChange={event => setTitle(event.target.value)}, but I'm not sure how to fix it. <Modal.Body> <form onSub ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

Is there a way to make a row stand out when it's clicked on

I have a data table with rows that I want to be able to highlight when clicked. The issue I'm facing is that the checkbox within each row is triggering the highlight event when clicked. How can I ensure that clicking on the checkbox only checks it wit ...

The error detected in the W3Schools validator pertains to CSS for audio elements that do not contain

Could somebody kindly explain why this code is being flagged as an error on w3schools? audio:not([controls]) { display: none; height: 0; } ...

Is it possible to leverage Create-React-App's npm start in conjunction with Node.js?

I've recently started diving into React and node.js. My goal is to have a node.js server that can serve up React.js pages/views. After running 'create-react-app' and then using 'npm start', I'm not sure if I also need to man ...

`Datatables sorting feature for British date and time`

I'm currently attempting to organize a column in a table using the DataTables plugin that contains UK date and time formats such as: 21/09/2013 11:15 Implementing Ronan Guilloux's code: jQuery.extend( jQuery.fn.dataTableExt.oSort, { "uk_dat ...

"Navigation Side Menu: w3-sidebar with hamburger toggle feature

If you are looking to implement the w3-sidebar, you can find it here: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_sidebar_over The existing code uses a "hanburger" icon to open the side menu and a "Close X" menu item to close it. To simpl ...

Find an idle event loop

Can you check for an idle event loop? Take these two examples: // Example 1 setInterval(() => console.log("hi"), 1000); // event loop not empty // Example 2 console.log("hi"); // event loop is now clear ...

In React JSX, what is the best approach for printing a substring?

I am facing an issue with dividing two variables in my React component. I need to display the result to only one decimal place, so I decided to use the substring method like this: <div className="col-md-8"> {(total_star / total_user).toString ...

Express router fails to mount

Struggling with my first project using expressjs, I have encountered an issue with a router not properly mounting. My approach involves the app mounting a router object which should then mount a second router object. While the first embedded router mounts ...

Experiencing unexpected outcomes via AJAX requests

Linked to: Query Database with Javascript and PHP This inquiry is connected to my previous question. I made adjustments to the PHP script based on one of the responses I received; however, when attempting to utilize $.getJSON, I encountered difficulties. ...

Navigating the use of PHP variables in JavaScript

Whenever I select an option from the menu, a Javascript function changes the input value based on a PHP variable. Below is an example of how I assign values from 1 to n to each option: $i = 0; foreach($videos as $val) { echo '<option value=&ap ...

When React first fetches data and users move to chat with each other, the state value does not update

Recently, I started learning about React and Node.js as I dive into building a chat application. When a user is clicked for one-on-one chat, I retrieve records from the database using backend Node.js and also incorporate socket.io. In my Chat.js file: imp ...

Configuring default media files in Docker with Django

After successfully deploying my Django web application using Docker and Docker Compose, Nginx, and Postgresql, I encountered an issue with the default media files. Previously, when deploying locally or on my server, I manually added the default media file ...

Injecting universal data into ValidationErrors in Angular

Trying to bind a value into ValidationErrors. Having this method: isUniqueEmail(control: FormControl): ValidationErrors { if (control.value != null) { console.log(control.value) if(control.value == this.foundEmail){ console ...

In Vue, it is not accurate to measure overflow

I am working on creating an overflow effect with tagging that fades out at the beginning to provide a subtle hint to users that there is more content. Here is what it currently looks like: https://i.stack.imgur.com/fXGBR.png To achieve this, I added a fa ...

Vue throwing ReferenceError when accessing uninitialized variable in Safari browser

Recently, I've encountered a perplexing error message that has me scratching my head. The error message reads as follows: ReferenceError: Cannot access uninitialized variable. This error specifically points to the line of code: const app = createApp(A ...

Issue with Mootools Ajax call and form submission

I'm dealing with a table that displays data from a database. I'm trying to implement a way to (a) delete rows from the table and (b) edit the content of a row in real-time. Deleting rows is working perfectly, but editing the content is proving to ...