The hover dropdown remains active even after the mouse has left

I've created a script for displaying a dropdown menu on small screens with a click (or tap on mobile), but I want it to change to hover when the screen size is larger. Here's my code:

$(document).ready(function() {
    var open = false;
    
      if ($(window).width() > 767) {
          $(".dropdown").hover(
             function(){
                 $('ul.nav li.dropdown:hover > ul.dropdown-menu').css('display','block');
                 console.log('display block de nav HOVER');
             });
      }
     else {
         console.log('smaller');

         $(".dropdown").click(
             function(){
                 if (open){
                     $('ul.nav li.dropdown:hover > ul.dropdown-menu').css('display','none');
                     console.log('display none de nav');
                 } else {
                     $('ul.nav li.dropdown:hover > ul.dropdown-menu').css('display','block');
                     console.log('display block de nav');
                 }

                 open = !open;

             });
        }
}); 

The HTML code:

<nav id="navbar" class="navbar navbar-default">
                <div class="container-fluid">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#typo-navbar-collapse-1" aria-expanded="false">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        @if(Sentinel::guest())
                            <a class="navbar-brand" href="{{ route('auth.login') }}">Typografics Academy</a>
                        @elseif(Sentinel::inRole('user'))
                            <a class="navbar-brand" href="{{ route('user.dashboard') }}">Typografics Academy</a>
                        @elseif(Sentinel::inRole('admin') || Sentinel::inRole('super'))
                            <a class="navbar-brand" href="{{ route('admin.dashboard') }}">Typografics Academy</a>
                        @endif
                    </div>

                    <div class="collapse navbar-collapse" id="typo-navbar-collapse-1">
                        <ul class="nav navbar-nav">

                            @if(!Sentinel::guest())

                                @if(Sentinel::inRole('user'))
                                    <li {{ Request::is('/results*') ? 'class=active' : ''}}><a href="{{ route('user.results') }}">Results</a></li>
                                @elseif(Sentinel::inRole('admin') || Sentinel::inRole('super'))
                                    <li {{ Request::is('admin/users*') ? 'class=active' : ''}}><a href="{{ route('users.overview') }}">Users</a></li>
                                    <li {{ Request::is('admin/tests*') ? 'class=active' : ''}}><a href="{{ route('tests.overview') }}" >Tests</a></li>
                                    <li {{ Request::is('admin/profiles*') ? 'class=active' : ''}}><a href="{{ route('profiles.overview') }}">Profiles</a></li>
                                    <li {{ Request::is('admin/results*') ? 'class=active' : ''}}><a href="{{ route('results.overview') }}">Results</a></li>

                                    @if(Sentinel::inRole('super'))
                                        <li {{ Request::is('admin/questions*') ? 'class=active' : ''}}><a href="{{ route('questions.overview') }}">Questions</a></li>
                                        <li {{ Request::is('admin/categories*') ? 'class=active' : ''}}><a href="{{ route('categories.overview') }}">{{trans('master.categories')}}</a></li>
                                        <li {{ Request::is('admin/companies*') ? 'class=active' : ''}}><a href="{{ route('companies.overview') }}">Companies</a></li>
                                    @endif

                                    <li class="dropdown">
                                        <a href="#" role="button" aria-haspopup="true" aria-expanded="false"> <span class="glyphicon glyphicon-plus"></span> Add New <span class="caret"></span></a>

                                        <ul class="dropdown-menu">
                                            <li {{ Request::is('admin/users/new') ? 'class=active' : ''}}><a href="{{ route('users.new') }}">{{trans('master.user')}}</a></li>
                                            <li {{ Request::is('admin/tests/new') ? 'class=active' : ''}}><a href="{{ route('tests.new.1') }}">{{trans('master.test')}}</a></li>
                                            <li {{ Request::is('admin/profiles/new') ? 'class=active' : ''}}><a href="{{ route('profiles.new') }}">{{trans('master.profile')}}</a></li>
                                            @if(Sentinel::inRole('super'))
                                                <li {{ Request::is('admin/questions/new') ? 'class=active' : ''}}><a href="{{ route('questions.new') }}">{{trans('master.question')}}</a></li>
                                                <li {{ Request::is('admin/categories/new') ? 'class=active' : ''}}><a href="{{ route('categories.new') }}">{{trans('master.category')}}</a></li>
                                                <li {{ Request::is('admin/subcategories/new') ? 'class=active' : ''}}><a href="{{ route('subcategories.new.without') }}">{{trans('master.subcategory')}}</a></li>
                                                <li {{ Request::is('admin/companies/new') ? 'class=active' : ''}}><a href="{{ route('companies.new') }}">{{trans('master.company')}}</a></li>
                                            @endif
                                        </ul>
                                    </li>
                                @endif
                             @endif
                        </ul>
                        @if(!Sentinel::guest())
                            <ul class="nav navbar-nav navbar-right">
                                <li><a class="userprofile" href="#">{{ucwords(Sentinel::check()->first_name)}}</a></li>
                                <li><a class="logout" href="{{ route('auth.logout') }}">Logout</a></li>
                            </ul>
                        @else
                            <ul class="nav navbar-nav navbar-right">
                                <li {{ Request::is('auth/login') ? 'class=active' : ''}}><a href="{{ route('auth.login') }}">Login</a></li>
                            </ul>
                        @endif
                    </div>
                </div>
            </nav>

Answer №1

Give this a shot:

$( document ).ready(function() {

    var isOpen = false;

      if ($(window).width() > 767) {
          $(".dropdown").hover(
             function(){
                 $(this).find('.dropdown-menu').css('display','block');
                 console.log('display block de nav HOVER');
             }, function() {
               $(this).find('.dropdown-menu').css('display','none');
             });
      }
     else {
         console.log('kleiner');

         $(".dropdown").click(
             function(){
                 if (isOpen){
                     $('ul.nav li.dropdown:hover > ul.dropdown-menu').css('display','none');
                     console.log('display none de nav');
                 } else {
                 $('ul.nav li.dropdown:hover > ul.dropdown-menu').css('display','block');
                     console.log('display block de nav');
                 }

                 isOpen = !isOpen;

             });
        }
});

Check it out here:

View the code: http://jsbin.com/wekepi/edit?js

Using jQuery method: .hover( handlerIn, handlerOut )

Reference: https://api.jquery.com/hover/

Answer №2

The reason behind this behavior is that the menu is instructed to show as a block only when hovered over, with no further action.

To solve this issue, simply assign a class named .block and use toggleClass on hover. This way, the class will be added and removed as needed.

.block { display:block; }

$(".dropdown").hover(
    function(){
        $('ul.nav li.dropdown:hover > ul.dropdown-menu').toggleClass('block');
        console.log('Displaying the nav HOVER block');
    });

Answer №3

Thanks to the guidance provided by @Surender Lohia, I was able to discover the perfect solution for the issue at hand.

$(document).ready(function () {

    var open = false;

    var displayBlock = function () {
        $('.dropdown-menu').css('display', 'block');
        console.log('The dropdown menu is now visible on hover over navigation.');
    };

    var displayNone = function () {
        $('.dropdown-menu').css('display', 'none');
        console.log('The dropdown menu is hidden when not hovered over navigation.');
    };
    var resizeEvent = function () {
        if ($(window).width() > 767) {
            $(".dropdown").hover(displayBlock, displayNone);
        } else {
            console.log('smaller');

            $('.dropdown').off();

            $(".dropdown").click(function () {
                if (open) {
                    displayNone();
                } else {
                    displayBlock();
                }

                open = !open;

            });
        }
    };

    resizeEvent();

    $(window).resize(resizeEvent);

});

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

Obtain JSON data using jQuery

Hey there! I am currently working on understanding how to retrieve data using json/JQuery with the code below. After storing a php variable in a json variable (var ar), I confirmed its contents through console.log, although when I used document.write it d ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...

In Node.js, when accessing a Firebase snapshot, it may return a

Currently, I am utilizing Firebase functions to execute the code for my Flutter application. This code is responsible for sending push notifications to my app. However, I am encountering an issue where I receive a null value at snap.val(). Take a look at h ...

Why do the fontawesome icons fail to appear in my SVG file?

I've encountered a peculiar issue where icons (from fontawesome) are not appearing in my svg. They have always displayed correctly on my personal computer, so for a while I didn't realize that others were having trouble seeing them. For instance ...

Choosing just the element that was clicked and added to the DOM

I've been experimenting with JQuery in a web app I'm developing. The app involves dynamically adding elements to the DOM, but I've encountered an issue with click events for these newly added elements. I'm looking for a way to target an ...

Error found in Nuxt3 application when using locomotive scroll functionality

I'm working on a Nuxt3 project with Locomotive Scroll and GSAP (repository link: https://github.com/cyprianwaclaw/Skandynawia-Przystan). I'm facing an issue where, when I change the page from index to test and then revert back, the page doesn&apo ...

Unicef's animated web content

Looking to learn more about gate animation and zoom page transition on the Unicef website? I want to incorporate these cool animations into my own project. Can someone provide me with a "keyword" or point me in the right direction to find information on ...

What is the best way to configure custom CSS styles in a React project?

I've been trying to position my Grid component from Material-UI, but so far, I haven't had any luck. What could be the issue here? class Scene extends React.Component { render() { const mystyle = { backgroundColor: "DodgerBlue", ...

Using Material-UI version 1, pass the outer index to the MenuItem component when clicked

Within my component, there is a Table that displays rows generated from a custom array of objects. In the last TableCell, I aim to include an icon button that, upon being clicked, opens a Menu containing various MenuItem actions (such as edit and delete). ...

Transformation of looks post a refresh

Initially, the CSS and appearance of the page look fine when I first open it (after clearing the cache). However, upon refreshing the page, a part of it changes (specifically, the padding direction of a div). This change occurs consistently with each refre ...

Substitute <br /> tags with a line separator within a textarea using JavaScript

Anyone have a quick fix for this? I've been searching online for a solution, but no luck so far. Already tried checking out: this, this Currently dealing with a textarea that receives data from AJAX call and it ends up looking like this: Hello& ...

What is the process for fetching a texture from a MySql database using three.js?

Is it possible to load a model's texture from a MySql database using three.js and php, based on the logged-in user? My goal is to display the texture on the model that corresponds to the current user. Can I simply use "echo" to retrieve the column con ...

Adjust the size of the image obtained from the JSON data

I am currently working on parsing JSON data which includes an image field that I want to adjust to a specific size. Despite my many attempts at tweaking the code, I seem to have lost track of why it is not functioning as desired. JSON var items=[]; ...

Achieve the hidden div scroll effect in React by initially hiding the div and then allowing

I am currently working on a web chat application using next.js. One of the features is an emoji picker button that, when clicked, displays a menu of emojis. The issue I am facing is that in order for the user to see the emoji menu, they have to scroll down ...

Tips for resolving issues with mat-autocomplete during scrolling

When I open the mat-autocomplete and scroll down the page, I would like for the mat-autocomplete to stay in place. ...

Having trouble with installing Node Windows NPM?

I'm attempting to install a simple package in Node.js, but when I use the standard command, it indicates that it cannot find the file or directory (refer to the image below). Despite updating and re-installing npm, the issue persists. I am using Windo ...

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

Column count pseudo class is malfunctioning on Safari browser

Why is the pseudo class with column count not working in the Safari browser? I have captured two screenshots to illustrate this issue. 1. Firefox browser screenshot https://i.sstatic.net/27uoI.png 2. Safari browser screenshot https://i.sstatic.net/vRN ...

Demonstration of implementing jq-idealforms in action

Can anyone provide a comprehensive example of how to use all the components of jq-idealforms? I've been struggling to make it work, even after closely following the demo page and reading through the GitHub documentation. I would greatly appreciate a l ...

Tips for creating a square HTML element

Looking to customize my react calendar with square tiles. Currently, the width is determined by the overall calendar width, but I want the height to match. https://i.sstatic.net/3vVrq.png Sample HTML: <button class="react-calendar__tile react-cal ...