Avoid activating jQuery functions based on certain screen widths for menu/navigation system

Recently, I've delved into the world of jQuery and attempted to create a simple menu system. The menu is designed to expand its submenu when hovering over the list item at screen widths larger than 480px, and to expand when clicking on the list item at widths less than 480px.

I thought I could utilize Modernizr's media query detection feature to enhance my code. However, my attempts have not been successful as seen in my demo here. Try hovering over the 'Properties' li tag to see the issue.

The problem seems to lie in the code's failure to recognize screen resizing properly. It functions correctly at >480px and <480px if you refresh the browser at those specific widths. But when you resize the browser, the functions still trigger incorrectly!!

Here's my code:

// Main nav dropdown animation

$(document).ready(function() {
  function doneResizing() {
    if(Modernizr.mq('screen and (min-width: 481px)')) {

        $("#sub-menu").hide();

        $("#show-investment-type-nav").hover(function() {
            $(this).find("#sub-menu").stop(true, true).slideDown("fast");
        }, function() {
            $(this).find("#sub-menu").stop(true, true).fadeOut("fast");
        });

    }
    else if(Modernizr.mq('screen and (max-width: 480px)')) {

      $("#sub-menu").hide();

      var next_move = "show";

        $("#show-investment-type-nav").click(function() {

            $('#sub-menu').slideToggle(100);

            if (next_move === "show") {
                $("body").addClass("nav-active");
                $("#site-nav #icon").empty().html("&#59236;");
                $("#site-nav #nav-margin-down").animate({"margin-top": "163"}, 100);
                next_move = "hide";
            } else {
                $("body").removeClass("nav-active");
                $("#site-nav #icon").empty().html("&#59238;");
                $("#site-nav #nav-margin-down").animate({"margin-top": "0"}, 100);
                next_move = "show";
            }
        });
    }
  }

  var id;
  $(window).resize(function() {
    clearTimeout(id);
    id = setTimeout(doneResizing, 0);
  });

  doneResizing();
});

If anyone can shed some light on why this glitch is happening, I'd greatly appreciate it! I'm eager to learn from my mistakes!

Thanks for your help!

Answer №1

Here is a revised version of the code that separates the click handler from the resize handler for better event handling. Moving next_move to the global scope may help and using data() to add values to menu elements could be a more efficient option:

var next_move = "show";

$(document).ready(function () {

    $("#show-investment-type-nav").click(function () {
        if (Modernizr.mq('screen and (max-width: 480px)')) {
            $('#sub-menu').slideToggle(100);
            if (next_move === "show") {
                $("body").addClass("nav-active");
                $("#site-nav #icon").empty().html("&#59236;");
                $("#site-nav #nav-margin-down").animate({
                    "margin-top": "163"
                }, 100);
                next_move = "hide";
            } else {
                $("body").removeClass("nav-active");
                $("#site-nav #icon").empty().html("&#59238;");
                $("#site-nav #nav-margin-down").animate({
                    "margin-top": "0"
                }, 100);
                next_move = "show";
            }
        }
    });

    function doneResizing() {
        if (Modernizr.mq('screen and (min-width: 481px)')) {
            $("#sub-menu").hide();
            $("#show-investment-type-nav").hover(function () {
                $(this).find("#sub-menu").stop(true, true).slideDown("fast");
            }, function () {
                $(this).find("#sub-menu").stop(true, true).fadeOut("fast");
            });
        } else if (Modernizr.mq('screen and (max-width: 480px)')) {
            $("#sub-menu").hide();  
            next_move = "show";
        }
    }

    var id;
    $(window).resize(function () {
        clearTimeout(id);
        id = setTimeout(doneResizing, 0);
    });

    doneResizing();
});

Answer №2

The issue appears to have been resolved with this solution, although it may be considered more of a temporary fix than a permanent one!

var move_next = "display";

$(document).ready(function () {

  // Implementation of touch device workaround to prevent submenu from being displayed during initial load
  $('#sub-menu').css("display","block");

    $("#show-investment-type-nav").click(function() {

      if (Modernizr.mq('screen and (max-width: 480px)')) {
        $('#sub-menu').slideToggle(100);
        if (move_next === "display") {
          $("body").addClass("nav-active");
          $("#site-nav #icon").empty().html("&#59236;");
          $("#site-nav #nav-margin-down").animate({"margin-top": "163"}, 100);
          move_next = "hide";
        } else {
          $("body").removeClass("nav-active");
          $("#site-nav #icon").empty().html("&#59238;");
          $("#site-nav #nav-margin-down").animate({"margin-top": "0"}, 100);
          move_next = "display";
        }
      }
    });

  function resizingCompleted() {
    if (Modernizr.mq('screen and (min-width: 481px)')) {

      // Hide the submenu
      $("#sub-menu").hide();

      // Reset margin for li tags in case the screen was expanded while the nav was open
      $("#site-nav #nav-margin-down").css("margin-top","0");

      $("#show-investment-type-nav").hover(function() {
          $(this).find("#sub-menu").stop(true, true).slideDown("fast");
      }, function () {
          $(this).find("#sub-menu").stop(true, true).fadeOut("fast");
      });
    } else if (Modernizr.mq('screen and (max-width: 480px)')) {

      // Resolves the touch device issue when tapping away from an expanded submenu... took quite a bit of trial and error!
      $('#sub-menu').slideUp(100);
      $("#site-nav #nav-margin-down").animate({"margin-top": "0"}, 100);

      // To ensure that if the nav is expanded and move_next = "hide", the hover event doesn't hide() the submenu
      if (!Modernizr.touch) {
        $("#show-investment-type-nav").hover(function() {
          $("#sub-menu").hide();
          if (move_next === "hide") {
            $("#sub-menu").show();
          }
        });
      }

      move_next = "display";
    }
  }

  var identifier;
  $(window).resize(function () {
    clearTimeout(identifier);
    identifier = setTimeout(resizingCompleted, 0);
  });

  resizingCompleted();
});

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

Exploring hash retrieval in Perl templates

What is the method for accessing variables in a hash when using Perl's HTML::Template module? As I construct the following hash in my Perl code: # Implementing success/error flash messages if ($query->param("submit")) { $template->param( ...

Error 107 occurred while attempting to parse JSON data using the AJAX technique with the REST API

I've encountered an issue while attempting to utilize the Parse REST API for sending push notifications. Every time I make an AJAX call, I receive an invalid JSON error in the response and a status code of 400. Below is my request: $.ajax({ url: & ...

Is it possible to merge the bind event for two selectors using jQuery?

I have the following: $('#loginLink') .bind('click', accessLinkClick); $('#registerLink') .bind('click', accessLinkClick); function accessLinkClick(e) { e.preventDefault(); $('# ...

The fadeOut() method causing issues with the visibility property

I am currently working on a feedback page that is displayed in a table with 3 columns. Name Feedback icons status ------------------------------------------------- Name1 icon1 icon2 icon3 Saved Name2 icon1 icon2 icon3 ...

I am encountering the error message "Utils is not defined" while attempting to generate a chart using chart.js

Attempting to replicate the example provided in chart.js documentation : link to example Unfortunately, I am encountering the error: Uncaught ReferenceError: Utils is not defined Despite its simplicity, I am struggling to identify the issue...! ...

Dynamic search form technology

My HTML view includes a search form and AJAX code to handle the form request $(document).ready(function() { console.log('Ready'); $('.search-wrapper').on('click', '#find-dates', function(a) { a. ...

What is the most effective way to implement a CSS stylesheet on a particular individual element?

Just starting out in web development and I recently experimented with a CSS stylesheet on a basic HTML element. It worked great when I targeted the element by name like this: label { color: green; } However, I wondered if there was a way to apply sty ...

Customizing textfield error color in MUI5 React based on conditions

I am looking for a way to dynamically change the color of error messages in my application, with warnings displaying in orange and errors in red. I prefer not to use useStyle as it is now deprecated in mui5. Below is the code snippet I have created: import ...

Why is the responseText from XMLHttpRequest always stripped of tags in AJAX?

Whenever the server sends the XML string to the client using the XMLHttpRequest object, I noticed that when I insert the text inside the div tags, it appears without any tags. However, I actually need the XML tags to be present so that I can parse the cont ...

employing personalized CSS styles

When I implement the following code: <div class="metanav"> ... </div> Every element inside that div will inherit the styling of .metanav. But if I duplicate .metanav in the CSS and rename it to A; then update the div's class to: <d ...

Is it possible to use Material-UI Link along with react-router-dom Link?

Incorporating these two elements: import Link from '@material-ui/core/Link'; import { Link } from 'react-router-dom'; Is there a method to combine the Material-UI style with the features of react-router-dom? ...

What is the best way to activate a function after all the AJAX calls within a function have finished executing?

My challenge lies in determining when all the AJAX calls have completed. Below is the function I am working with. function getValuesForTablePropertySelected(questionList, itemsArray) { for (var i = 0; i < itemsArray.length; i++) { switch (i ...

Using JavaScript to transform radio buttons into checkboxes

I have a grouping of radio buttons and a checkbox displayed on the page as shown below <html> <head> <title>Languages</title> <script type="text/javascript"> </script> </head> <body> <spa ...

Steps for positioning a logo to the left and navigation to the right with HTML and CSS

Could someone assist me in aligning a logo on the left and navigation menu on the right using HTML and CSS? I envision it to look like the image displayed. I have tried various approaches to adjust my CSS styling, but nothing seems to be working as inten ...

What is the memory allocation for null values in arrays by node.js?

Continuing the discussion from this thread: Do lots of null values in an array pose any harm? I experimented with node.js by doing this: arr=[] arr[1000]=1 arr[1000000000]=2 arr.sort() However, I encountered the following error: FATAL ERROR: JS Alloca ...

What is the proper way to encode image URLs for use in CSS?

For the div element in my code, I want to allow users to input a URL that will be applied as a CSS background image, like this: background-image: url("/* user specified URL here*/") I'm concerned about security. How can I properly escape the URL to ...

Error 403: ACCESS DENIED - The server comprehended the inquiry, yet declines to carry it out

Encountering a persistent 403 error when making an AJAX call to an API. This issue is specific to Microsoft Edge, while other browsers like IE, Chrome, Firefox, and Safari work without any errors. The page doesn't utilize bootstrap, as there have be ...

Sending data from one HTML element to another using JQuery's Ajax function

I'm currently attempting to pass the value from an anchor tag into an ajax function. This is the HTML code I am working with <section> <div class="nav-section"> <nav> <ul> <li>< ...

Comparison between modules and standalone components

It has come to my attention that there is a growing trend in Angular 17 to move away from using modules, opting instead for standalone components. This approach makes Angular more similar to Vuejs or React, where the concept of modules is not as prominent. ...

Master Angular Autocompletion

Looking to add a filter autocomplete feature but unsure of how to implement it. Any assistance would be greatly appreciated! I've come across some examples, but they don't quite fit my needs. Here's the snippet of code: <mat-form-field c ...