Is it possible to automatically close navigation dropdowns when the screen size changes?

I am using a bootstrap 4 navbar with dropdowns that open with CSS animation/fade-in on desktop, and a separate toggle button for mobile. Everything works fine, but when I open the dropdowns on mobile and then resize the window screen, they remain open which doesn't work well with the animation. Is there a way to automatically close the dropdowns when the window is resized or reaches the desktop breakpoint?

HTML:

<ul class="navbar-nav">
<li class="nav-item dropdown">
    <div class="nav-title-flex-container">
        <a class="nav-link dropdown-toggle" data-toggle="dropdown" href=“home.html"
           id="navbar-drop-downs"
           aria-haspopup="true" aria-expanded="false">
            <span class="underline"> Home</span>
        </a>
        <span class="openNav"><i class="fa fa-angle-right"></i></span>
    </div>

    <div class="dropdown-menu dropdown-menu-nav-bottom"
         aria-labelledby="navbar-drop-downs">
        <a class="dropdown-item" href=“#”>Sub Page</a>
        <a class="dropdown-item" href=“#”>Sub page</a>
    </div>
</li>
<li class="nav-item dropdown">
    <div class="nav-title-flex-container">
    <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="how-to-be-vocal.html"
       id="navbar-drop-downs"
       aria-haspopup="true" aria-expanded="false">
        <span class="underline”>About </span>
    </a>
        <span class="openNav"><i class="fa fa-angle-right"></i></span>
    </div>
    <div class="dropdown-menu dropdown-menu-nav-bottom"
         aria-labelledby="navbar-drop-downs">
        <a class="dropdown-item" href=“#”>Sub Page</a>
    </div>
</li>
</ul>

CSS:

@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}


@media (min-width: 1199px) {
  .dropdown:hover > .dropdown-menu {
    display: block;
    z-index: 100;
    position: absolute;
    animation: fadein .7s;
  }
}

JQuery: (toggling dropdowns/mobile)

  $openNavToggle.on('click', function () {
  $(this).parent().next('.dropdown-menu-nav-bottom').toggleClass('show');
  $(this).find('i').toggleClass('fa-angle-right--active');
});

Answer №1

To utilize the jQuery resize event handler, follow these steps.

Ensure that you are removing classes instead of just toggling them; otherwise, the navigation may unexpectedly appear during resizing.

$openNavToggle.resize(function () {
  $(this).parent().next('.dropdown-menu-nav-bottom').removeClass('show');
  $(this).find('i').removeClass('fa-angle-right--active');
})

Add a debouncing mechanism to the resize function to ensure it only takes effect at the end of the resizing process:

let resizeEvent;
$openNavToggle.resize(function () {
  clearTimeout(resizeEvent);
  resizeEvent = setTimeout(() => {
    $(this).parent().next('.dropdown-menu-nav-bottom').removeClass('show');
    $(this).find('i').removeClass('fa-angle-right--active');
  }, 300);
})

Answer №2

One way to handle changes in window size is to listen for the resize event:

window.addEventListener('resize', (e)=>{
    // Perform your show/hide functions here.
    // You can also check the new width and apply specific logic accordingly.
});

Answer №3

Here is a simple method to hide content:

function hideContent() {
   $(this).parent().next('.dropdown-menu-nav-bottom').toggleClass('hide');
   $(this).find('i').toggleClass('fa-angle-right--inactive');
}

Attach it to the resize event:

$(window).resize(hideContent);

Answer №4

Yes, you have the option to utilize the window resize event for this purpose.

You can then verify if the size meets the necessary dimensions and take appropriate action.

To enhance performance, a commonly employed technique is using the debounce method in combination with it:

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

I am encountering an issue with Angular where the following error message is displayed: "src/app/app.component.html:18:20 - error TS2339: Property 'DepScreen' does not exist on type 'AppComponent'"

This code snippet is from my app.component.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...

Adjusting the array of buttons with various functions within the Header component

I am looking to create a customizable Header component with different sets of buttons that trigger various functions. For example, on the home page, the buttons could be "visit about page" and "trigger vuex action A", while on the about page they could be ...

Guide on stacking two divs on each other in response to a decrease in screen width

In this particular section, there is a div labeled programDescriptionDiv. Inside programDescriptionDiv, there are two separate divs. Normally, these two divs each take up 50% of the screen width. The goal is to have the second div stack below the first on ...

Developing asynchronous DOM functions for optimal performance

Imagine having a large amount of data that needs to be processed. In this scenario, the processing must happen on the client side rather than the server side. The data processing involves iterating through each element in the data set: for element in data ...

Navigational menu that slides or follows as you scroll

Wondering if anyone knows of a straightforward jQuery or Javascript method to create a navigation sidebar that smoothly moves with the user as they scroll down a page. A good example can be found here: Any suggestions would be greatly welcome. ...

Having trouble with clearing divs function not working as expected

I'm facing a challenge in properly aligning 3 div elements without resorting to adding padding at the bottom of the wrapping div, which isn't the most practical solution. Check out the issue demo here How would you suggest addressing this parti ...

Using ng-repeat within another ng-repeat allows elements to be displayed as siblings

My goal is to create a structured list using angularjs: Parent 1 Group1 Child1 Child2 Child3 Child4 Group2 Child1 Child2 Parent 2 Group1 Child1 Child2 Group2 Child1 I have data organized in a similar format like this. $scope.parents = [{ name:&apos ...

Showing JSON response on an HTML page using AngularJS

I have limited experience with JavaScript and/or Angular, but I am required to utilize it for a research project. My task involves showcasing the JSON data returned by another component on a webpage. Here is how the process unfolds: When a user clicks on ...

Issue occurs when a circle element is not following a div element on mouse

Currently, I have implemented some jQuery code that instructs a div named small-circle to track my cursor movement. I discovered how to accomplish this by referencing a thread on stack overflow. I made slight modifications to the script to suit my specifi ...

No results found for the xpath within the <p> tag

I'm currently using selenium.webdriver chrome to scrape data from my website, and I need to extract the location details of visitors. Although I have successfully identified the <p> tag that contains 'location', it is returning None. ...

When hovering over an element in Firefox, the mouse event triggers twice causing a flicker. Is there a solution to prevent this flickering issue?

CSS: <ul class="navigate"> <li> <a title="Demo01" href="###">Demo01</a> <ol> <li><a title="Demo01Children01" href="###">Demo01Children01</a></li> <li><a title ...

How come my web page is not displaying the guages from guage.js?

I am utilizing guage.js to create a graph based on this Fiddle. However, upon adding the same code to my website, the rendering does not appear as expected: Upon inspecting in Chrome developer tools, I noticed that the element still exists but lacks heigh ...

Examining REST API functionality through the use of a Console, requiring an integer list as a parameter

Currently, I am in the process of testing a REST API to perform an action that requires a list of integers. I am uncertain about how to correctly handle the parameters required for this test. In my request payload, I have included the following: idAttac ...

Tips for submitting a form after a successful transaction with PayPal

My HTML page has a form with a PayPal button and a PayPal credit card button. This is a basic HTML and JavaScript site, not an online store. How can I automatically submit the form after a successful payment? The onApprove part of my code below is not fu ...

Using a combination of radio buttons and JavaScript to adjust the color of a div element

Currently, I am experimenting with radio buttons to modify the background color of my div tag. My goal is to incorporate more than one condition. For example, if button A and button B are both clicked, then change the color to green. This is what I have im ...

Troubleshooting: Node.js not receiving data from HTML form

I am currently facing an issue with my HTML form and Node.js server. Despite implementing a form that is supposed to send data to the server, no information is being transferred. The form successfully makes a request, but it fails to send any form data alo ...

Using setTimeout with jQuery.Deferred

I decided to experiment with jQuery Deferred and setTimeout by creating a basic list. <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> In my script, I ...

Unable to render the JSON data that was retrieved from a jQuery AJAX request

I am having trouble displaying JSON data that is returned from an AJAX call. Can someone please assist me? I am new to this. $.ajaxSetup({ cache: false, timeout: 5000 }); //String.prototype.toJSON; var the_object = {}; function concatObject(obj) { ...

Add axios requests to the axios.all array

Good evening. I am currently trying to insert an array into the axios.all([]) structure! This is the code snippet I am working on: app2.js new Vue({ el: '#central', data: { estilo: 'resize:none;text-align:center;color: ...

Align dropdown navigation menu/sorting dropdown in the same position as the button

Exploring the world of dropdown menus in CSS has led me to encounter some challenges. I am striving to ensure that the dropdown boxes appear on the same line as the button that triggers them. Below is the CSS code I have been working with: /* global style ...