Limitations of jQuery: onClick function not transferable

I am struggling to achieve the following functionality for my navbar dropdown menus:

  • When the screen size is greater than 992px, I want the navbar dropdowns to open on mouse enter.
  • For screens smaller than 992px, I want the dropdowns to open on click.

The problem I'm facing is that everything works correctly initially. However, after closing the dropdown by clicking its heading for a second time, I can no longer reopen it.


          $(document).ready(function() {
            function windowSizeCheck() {
              var $windowSize = $(window).width();
              if ($windowSize > 992) {
                $('.dropdown').mouseenter(function() {
                  $(this).children('.dropdown .dropdown-menu').slideDown('slow');
                  $(this).children('.dropdown .dropdown-menu').toggleClass('open');

                  $(this).mouseleave(function() {
                    $(this).children('.dropdown .dropdown-menu').stop(true).slideUp('fast');
                    $(this).children('.dropdown .dropdown-menu').removeClass('open');
                  });
                });
              } else {
                $('.dropdown').on('click', function() {
                  $(this).children('.dropdown .dropdown-menu').slideDown('slow');
                  $(this).children('.dropdown .dropdown-menu').toggleClass('open');
                  $(this).css({
                    'max-height': '400px',
                    'overflow-y': 'auto'
                  });

                  $(this).on('click', function() {
                    $(this).children('.dropdown .dropdown-menu').stop(true).slideUp('fast');
                    $(this).children('.dropdown .dropdown-menu').toggleClass('open');
                  });
                });
              }
            }
            windowSizeCheck();
          });
        
      
.open {
          display: block;
        }
      

          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.js"></script>
          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />
          <nav class="navbar navbar-expand-lg navbar-light bg-white px-2 py-0 shadow-sm fixed-top">
            <a href="#" class="navbar-brand">Brand Name</a>
            <button type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbars" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler">
              <span class="navbar-toggler-icon"></span>
            </button>
            <div id="navbarContent" class="collapse navbar-collapse">
              <ul class="navbar-nav">
                <!-- Dropdown menu items -->
              </ul>
              <ul class="navbar-nav ml-auto">
                <li class="nav-item"><a href="" class="nav-link text-uppercase"><i class="fas fa-shopping-cart"></i></a></li>
              </ul>
            </div>
          </nav>
        
      

Answer №1

Some points to note:

  • The screen size detection was previously only happening on document load, I have added a window resize event to reevaluate the $windowSize value.
  • The inline properties max-height and overflow-y have been replaced with a class named openNav.
  • An inline property display:block was causing issues with closing the navigation menu on click (on screens less than 992px).
  • Transitioning from desktop to mobile view also requires unbinding the mouseenter and mouseleave events.

Find the working code snippet below:

$(document).ready(function() {
  function windowSizeCheck() {
    var $windowSize = $(window).width();

    if ($windowSize > 992) {
      $('.dropdown').mouseenter(function() {
        // code here...
      });
    } else {

      // Code for mobile view

    }
  }

  // Run window size check on document load
  windowSizeCheck();

  $(window).on('resize', function() {
    // Re-run window size check on resize
    windowSizeCheck();
  });

});
.open {
  display: block;
}

.openNav {
  max-height: 400px;
  overflow-y: auto;
}
.dropdown-menu{
min-width: max-content !important;
}

@media screen and (max-width:767px){
.dropdown-menu{
min-width: 10rem !important;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />

// HTML content...

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

Maintain the initial value using ko.mapping.fromJS

How can I prevent new data fetched from an AJAX call using ko.mapping.fromJS from replacing the existing data in my observableArray? I want to append the new data without losing the previous entries. function ViewModel() { var self = this; self. ...

Hovering over the top menu items in AngularJS will reveal dropdown submenus that will remain visible even when moving the cursor

I am facing an issue where my top menu has links that display a dropdown of additional menu items upon hovering. I have attempted to use onmouseover and onmouseleave events to control the visibility of the sub menu. However, I have encountered a problem ...

JSON data cannot be transmitted using AJAX

I created a function that tracks the time spent on a specific page and where the user came from. The data is collected and saved into a JSON object, but I encountered an issue when trying to send this JSON via ajax. Upon successful sending, I receive an em ...

What is the best way to fill the MongoDB post schema with every comment for the post?

I have created two schemas, one for posts and another for comments. const PostSchema = new Schema( { title: { type: String, required: true }, text: { type: String, required: true }, author: { type: Schema.Types.ObjectId, ref: 'User' ...

Is it possible to repeat this action by swiping to the left?

I'm currently developing an app in PhoneGap and retrieving information using JSON. My goal is to trigger this function again with Ajax when I slide left. This is the code I have so far. Thank you to everyone for your assistance. $(document).ready( ...

Issues with div misalignment during jQuery animation

I have successfully created an animation where a child div inside a parent div moves up by -60px when the mouse enters the parent div, and returns to its original position when the mouse leaves. However, I am facing an issue where if the mouse moves direct ...

I am experiencing an issue where the Mongo item ID is not being successfully passed through the REST API

Recently, I've been working on developing a blog site for my class project. The main goal is to create a REST API for the blog site. I have successfully managed to display data from the database using .ejs views, except for one issue. I am facing diff ...

Ways to position a button at the bottom of a Bootstrap card

In the card layout, I am struggling to position the red button at the bottom of the column despite using margin auto. Can anyone provide a solution for this issue? Thank you in advance! <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a ...

"ModuleNotFound" error occurred when attempting to utilize Netlify lambda functions with external dependencies

https://i.stack.imgur.com/vVmky.jpg I'm currently exploring the capabilities of Netlify, specifically its lambda function feature for running a node function with dependencies. Following a tutorial from CSS-Tricks, my functions/submission-created.js ...

Having trouble submitting data to a NextJS API route?

I am currently working on a simple form within a NextJS page, where the data is being stored in state: const [bookingInfo, setBookingInfo] = useState({ name: "", email: "", phone: "", }); const handleChange = (e ...

Configuration object for Webpack is not valid

I encountered an error while using webpack that says: Invalid configuration object. Webpack has been initialized with a configuration object that does not conform to the API schema. - configuration.resolve has an unknown property 'extension&ap ...

CSS code preventing hyperlink from functioning

My website is almost complete, but I'm running into an issue with some hyperlinks on my event registration page. The first link works fine, but the second one does not. To troubleshoot, I created a test page with just the two links and still encounter ...

Turning spring form data into a JSON object via automation (with a mix of Spring, jQuery, AJAX, and JSON)

Recently, I've set up a spring form that utilizes ajax for submission. Here's an overview of my form... <form:form action="addToCart" method="POST" modelAttribute="cartProduct"> <form:input type="hidden" ...

Just started working with React and encountered this initial error message in my project

Welcome to Windows PowerShell! Upgrade to the latest version of PowerShell to enjoy new features and enhancements! PS D:\React> cd textutils PS D:\React\textutils> npm start npm WARN config global `--global`, `--local` are deprecated ...

Removing negative numbers from Jquery Mobile Forms is essential for ensuring accurate and efficient

Greetings in Jquery Mobile form input field <div data-role="fieldcontain"> <label for="price">Price:</label> <input id="priceField" name="price" type="number" data-role="none" value="{{price}}" > </div> Encountering ...

Ensuring the consistency of actions through thorough testing

Currently utilizing xstate for the implementation of a login flow. Within my machine, the initialState triggers a Promise, which redirects to a state with an entry action if rejected. I am seeking to properly test the timing of when this action is called. ...

Changing the background color of the canvas using Javascript

I want to create a rect on a canvas with a slightly transparent background, but I don't want the drawn rect to have any background. Here is an example of what I'm looking for: https://i.stack.imgur.com/axtcE.png The code I am using is as follo ...

NodeJS - The server returns a 404 error before ultimately displaying the requested page

I'm having trouble with my nodeJS application. When I make an asynchronous call using ajax, the server first responds with a 404 error before loading the page. The application functions properly, but I keep receiving repetitive logs stating "Can' ...

passing arguments during deferred resolve() and when() operations

I am currently working on a flash card website and I need to determine the status of preloaded images once they have finished loading or if there was an error. After obtaining the status of each image, I will proceed with further actions. My code is inspi ...

The functionality of React setState seems to be malfunctioning when activated

Having encountered an unusual issue with react's setState() method. Currently, I am utilizing Azure DevOps extensions components and have a panel with an onClick event that is intended to change the state of IsUserAddedOrUpdated and trigger the addOr ...