Seeking guidance on implementing toggle buttons for navigation bar items on mobile screens, enabling them to toggle for a dropdown menu. The tools at my disposal are HTML, CSS

I want to make the navigation menu responsive by adding a toggle button for the dropdown menu on mobile screens. Here is the code snippet:

.nav-link {
  display: inline-block;
  position: relative;
  color: black;
}

html,body{
  height: 100%;
  width: 100%;
  font-family: 'Poppins', sans-serif;
  color: #222;
}
.navbar{
  padding: .8rem; 
}




.navbar {
  padding-right: 15px;
  padding-left: 15px;
}
.navbar .container {
  width: auto;
}


.cart {
  position: absolute;
  right: 5%;
  background-color: Transparent;
  background-repeat:no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
}
.navbar-nav li:first-child{
  display: none;
}

@media (max-width: 768px) {    

.navbar {
border-radius: 4px;
padding-right: 0;
padding-left: 0;
}

.navbar-brand{
  align-items: center;
  padding-right: 10%;
}

.navbar-nav li:not(:first-child){
    border-bottom: 1px solid #000;
}

.navbar-nav li:first-child{
    display: block;
}


#myNavbarToggler13 {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999999;
    width: 75%;
    height: 100%;
    background-color: #f9f9f9;
    overflow: auto;
    bottom: 0;
    max-height: inherit;
}

.nav-item{
    transition: 0.3s;
    padding: 5px 35px 0px;
    /*margin: 5px 0 0 50px;*/
}

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">


<nav class="navbar navbar-expand-md navbar-light bg-light sticky-top" role="navigation">
<button class="navbar-toggler" type="button" data-toggle="slide-collapse" data-target="#myNavbarToggler13"
      aria-controls="myNavbarToggler13" aria-expanded="false" aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
  </button>
<a class="navbar-nav navbar-brand mx-auto" href="#"><img id="logo">Brand
  <button class="cart" type="button" data-toggle="slide-collapse" data-target="#cartToggler"
      aria-controls="cartToggler" aria-expanded="false" aria-label="cartToggle navigation">
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-bag-fill" viewBox="0 0 16 16">
    <path d="M8 1a2.5 2.5 0 0 1 2.5 2.5V4h-5v-.5A2.5 2.5 0 0 1 8 1zm3.5 3v-.5a3.5 3.5 0 1 0-7 0V4H1v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V4h-3.5z"/>
  </svg>
  </button>
</a>

  <div class="collapse navbar-collapse" id="myNavbarToggler13">
      ...
  </div>

  <div class="collapse navbar-collapse" id="cartToggler">

  </div>
</nav>
<script>
    $(".navbar-toggler ").on('click', function() {
        $navMenuCont = $($(this).data('target'));
        $navMenuCont.animate({
            'width': 'toggle'
        }, 350);
        $(".menu-overlay").fadeIn(500);
    });
    $(".menu-overlay").click(function(event) {
        ...
    });
    $("#crossButton").click(function(event) {
        ...
    });

</script>

Answer №1

If you want to manipulate elements on your webpage using jQuery, you can make use of selectors like parent, siblings, and children to toggle their display as needed.

Keep in mind: To ensure this functionality works correctly, remember to eliminate any href attribute from the dropdown toggle element; otherwise, it may redirect you to a different page unintentionally.

See an example below:

$(".navbar-toggler ").on('click', function() {
    $navMenuCont = $($(this).data('target'));
    $navMenuCont.animate({
        'width': 'toggle'
    }, 350);
    $(".menu-overlay").fadeIn(500);
});
$(".menu-overlay").click(function(event) {
    $(".navbar-toggler").trigger("click");
    $(".menu-overlay").fadeOut(500);
});
$("#crossButton").click(function(event) {
    $(".navbar-toggler").trigger("click");
    $(".menu-overlay").fadeOut(500);
});

$('.nav-item .nav-link').click(function(){
  $(this).siblings('.dropdown-menu').slideToggle();
  $(this).parent().siblings('li').children('.dropdown-menu').hide();
});
.nav-link {
  display: inline-block;
  position: relative;
  color: black;
}

html,body{
  height: 100%;
  width: 100%;
  font-family: 'Poppins', sans-serif;
  color: #222;
}
/* Additional CSS rules go here */
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/js/bootstrap.min.js"></script>
<!-- HTML structure for navbar -->
<nav class="navbar navbar-expand-md navbar-light bg-light sticky-top" role="navigation">
<!-- Navbar content goes here -->
</nav>

For further details on jQuery's sibling selection method, refer to: https://api.jquery.com/siblings/

To explore more about parent elements in jQuery, visit: https://api.jquery.com/parents/

Learn about selecting child elements with jQuery at: https://api.jquery.com/children/

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

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

The Model Viewer module is unable to load the three-dimensional model

Attempting to incorporate a 3D model into my website using the modelviewer library, but encountering difficulties in loading the file as shown below: Just to note, I am utilizing github pages with a custom domain from godaddy which may be contributing to ...

How can I implement a single Ajax call to load content from various pages and display it

This code facilitates an ajax call to dynamically change the content of a div in the main page without requiring a full page reload: function ajaxcall() { $.ajax({ type: "POST", url: "/create.php", success: function( returnedDa ...

Why are the variables not reflecting the changes when an event is triggered?

I'm a beginner in programming and would really appreciate some guidance. Why are my variables not updating when I click the button?? Here is the HTML code snippet: <h1>NIM</h1> <p>Welcome to a simple edition of the game NIM</p& ...

What is the most efficient way to extract dynamically generated JavaScript content from a webpage?

Currently, my method involves using selenium alongside PhantomJS to scrape dynamic content generated by JavaScript on a website. Although it provides me with the desired results, the process is quite slow as I have to wait for the entire page to load befor ...

Tips for transforming a nested for-loop into a recursive function

Trying to work with Memcached data in Node.js is proving to be a challenge due to the asynchronous nature of the language. My goal is to store all retrieved results in an object. This is how I would typically approach it: for( x = startX; x <= endX; x ...

Loading images with CSS media queries is an essential technique for optimizing

Currently, I am exploring options to dynamically load a background image based on the width of the browser window. This way, I can optimize bandwidth usage by only loading the image that will be displayed. I am aware that using the HTML picture tag allows ...

Issues with implementation of map and swiper carousel functionality in JavaScript

I am trying to populate a Swiper slider carousel with images from an array of objects. However, when I use map in the fetch to generate the HTML img tag with the image data, it is not behaving as expected. All the images are displaying in the first div a ...

Responsive Bootstrap 4 Login Form with customized top height

This login form was created using Bootstrap 4, starting with a preset that I then customized to fit my needs. As someone new to Bootstrap and CSS, I struggled with making the form responsive. When resizing the window, the top portion gets cut off and is no ...

Having issues with the presentation of full_numbers pagination in IE while using jQuery dataTables

I am currently utilizing the DataTables jQuery plugin (found at ) with the initialization code below: $('#reconcile_table').dataTable( { 'bSort' : true, 'bFilter' : true, 'bSortClasses' : false, &a ...

What purpose does the array.pop()!(object) syntax serve within Codemirror?

Within the Codemirror 6 documentation and at line 41 of the code, there is a snippet that reads: while (pending.length) pending.pop()!(data.updates) I'm curious about the meaning of this syntax. It appears to be TypeScript specific. How would this lo ...

Utilizing JQuery Template to Invoke JavaScript Functions

If I have the following JSON object structure: ITEMS is an array with one element, and FILTER is another array with 3 items in it. Description: "churches with some restrictions" ITEMS: {...} [0]: {...} FILTER: {...} ...

What is the best way to select and style individual HTML elements using CSS?

Having trouble editing a Validations Form in Ionic 4 with CSS. It seems that only the form elements are targeted after clicking on the form group. Attached below are the form states before and after click. I'm unable to style the form elements before ...

A guide on extracting the geometry from an STL model imported into three.js

After using STLLoader to load an STL file into three.js, I am trying to access the vertices and geometry of the model for further use. However, I am encountering difficulty in retrieving the geometry after calling the loader. How can I achieve this? Belo ...

No data is being retrieved by SWR

I'm struggling to make SWR work in my code. Despite trying multiple examples, I can't seem to get it functioning properly. It's frustrating because the code looks fine and should work. I feel like I must be missing something simple. Current ...

How to iterate through two arrays using AngularJS ng-repeat

I have been attempting to create a specific layout by iterating through two arrays However, the output I am receiving from the ng-repeats does not match my desired view Below is the current code that I am working with: $scope.properties = ["First name", ...

Positioning a text field and a button adjacent to each other within the same row

My challenge is to consistently position a textfield and a button side by side. The requirement is for the button to always be on the right side of the screen, while the textfield should take up the remaining width on the left side. I initially tried setti ...

Navigate through dropdown options using arrow keys - vuejs

I am currently working on creating an autocomplete feature using Vue.js. However, I have run into an issue with the scroll animation. The goal is to enable scrolling by clicking on the arrow keys in the direction of the key pressed, but the scroll should ...

I'm using Bootstrap (version 5.3) and when I tried to replicate the features from the examples, I noticed that the background isn't being copied over

I encountered an issue today while working on a website using bootstrap. I was copying features from examples in the bootstrap section, but when I pasted the code into my coding platform, the background appeared transparent and did not display as expected. ...

If the currency is not in USD, please refrain from using the $ symbol before the amount

Is it possible to modify this function so that when the currency is not USD, the $ sign is not added in front of the amount? var convertToCurrency = number => { if (!number) return ''; return new Intl.NumberFormat('en', { ...