Menu remains open on resizing browser, refusing to close

Welcome to my code snippet: HTML:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8>
    <title>Responsive Menu</title>

   <!-- CSS and JS link tags go here -->

</body>
</html>

CSS:

body {
    font-family: "Ludica Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
}

<!-- CSS styles for various elements go here -->

JavaScript:

$(document).ready(function(){ 
    var headerHeight = $("#topbar").height();

    $(".nav-trigger").click(function() {
        $(".mobile-menu").slideToggle(400)
    });

    $(".mobile-menu").css("top", headerHeight);

    $("#wrapper").css("top", headerHeight);
}); 

If the dropdown menu is open when the screen width exceeds 900px, it should automatically close. How can I achieve this functionality?

Thank you!

Answer №1

When you click on the menu bar icon, JavaScript is used to toggle the display. This overrides the 'display' CSS for .mobile-menu to some extent, as it changes the style after the CSS has already loaded. To maintain the responsive .mobile-menu CSS, you should toggle the UL display value (child) instead of the .mobile-menu (parent). I believe this is what the example site you mentioned does.


<nav class="mobile-menu">
    <ul class="mobile-menu-items">
        <li><a href="#">Home</a></li>
        <li><a href="#">Work</a></li>
        <li><a href="#">Contact Me</a></li>
    </ul>
</nav>

For the .mobile-menu, keep the CSS as display: none on large screens and display: block for smaller screens. Initially set the new class ".mobile-menu-items" to display: none, then toggle it with jQuery:


$('.nav-trigger').click(function(){
    $('.mobile-menu-items').slideToggle();
});

Alternatively, you can toggle the visibility instead of the display:


$('.nav-trigger').click(function(){
  if ( $('.mobile-menu').css('visibility') == 'hidden' )
    $('.mobile-menu').css('visibility','visible');
  else
    $('.mobile-menu').css('visibility','hidden');
});

Answer №2

To ensure the mobile menu retracts instead of just being hidden in CSS when the window width increases, you can implement the following code:

var $window = $(window), // storing objects for better performance
    $mobileMenu = $(".mobile-menu");

$window.resize(function(){

  if( $window.width() > 900) $mobileMenu.slideUp();

})

Answer №3

Here is an updated and very basic example of resizing elements on a webpage:

ul{list-style-type:none;}

@media screen and (min-width: 500px) {
  
  #big li{display:inline-block;width:100px;height:32px;border:1px solid red;}
  #small{display:none;}
  
}

@media screen and (max-width: 500px) {
  
  #big{display:none;}
  #small{display:block;}
  .smaller{display:none;}
  #small li:hover~ul{display:block}
  .smaller:hover{display:block;}
  
  }
<ul id="big">
  <li>1</li>
   <li>1</li>
   <li>1</li>
   <li>1</li>
  </ul>
<ul id="small">
  <li>home1</li>
        <ul class="smaller">
          <li>3</li>
          <li>3</li>
          <li>3</li>
          <li>3</li>
        </ul>

   <li>home2</li><ul class="smaller">
          <li>3</li>
          <li>3</li>
          <li>3</li>
          <li>3</li>
        </ul>
  </ul>

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

Struggling with a JQuery function that fails to perform addition

I'm experiencing an issue with my code where the math doesn't add up when trying to sum values under the venting selection. Instead of adding up, it just displays as text. I have an event set up that should populate the values upon selecting valu ...

The challenge of maintaining scope in AngularJS Bootstrap Modals

In my application, I am using ngRoute to load a template that includes a bootstrap modal dialog. The purpose of this modal is to prompt the user if they are sure about losing their changes when trying to leave the row they are currently editing in a table. ...

jQuery - Ajax script exhibiting unexpected behavior

I've been troubleshooting my code and can't figure out what's going wrong. The syntax seems correct to me - essentially, if there is a div named 'map_canvas' on the page, then the function initialize_google_maps should be invoked. ...

How can you decode JSON using JavaScript?

Need help with parsing a JSON string using JavaScript. The response looks like this: var data = '{"success":true,"number":2}'; Is there a way to extract the values success and number from this? ...

The CSS3 Animation-fill-mode: An Essential Property

I am working on a cool effect where text slides into the window and remains in place after the animation is complete. Surprisingly, I have managed to get the animation to work on one part of the text, but for some reason, the second part is not cooperating ...

What is the best way to extract text from a list item in an unordered list (

I am trying to search a ul list that populates a ddSlick dropdown box. ddSlick adds pictures to list items, making it a visually appealing choice. To see more about ddSlick, you can visit their website here: Here is the code I am using to loop through the ...

TYPESCRIPT: The argument labeled as 'typeof X' cannot be assigned to the parameter labeled as 'Y' that extends

As I venture into coding with TypeScript, I am encountering some compilation issues. It appears that I am facing a hierarchy problem with several classes. The first class (A) defines a set of properties/functions. The second class (B) inherits from class ...

Dirty context detected in Material-UI TextField

Trying to understand how to check for dirtyness with material-ui's FormControl or TextField component. The TextField demo page mentions that TextField is made up of smaller components (FormControl, InputLabel, Input, and FormHelperText) which can be c ...

What is the best way to perform a keyword search in AngularJS?

My data consists of code:description pairs (e.g. cmsc100: Web Programming). I have a search box where users can enter either the code or description. Upon clicking the button, the program should display the data that matches the entered code/description or ...

Separating an Array Subset in JavaScript/jQuery

I need to filter a specific part of a javascript array containing objects by a particular condition, such as: object.property == 2 Instead of manually building a new array with the matching items, I am curious if there is a shortcut for this process. ...

What is the best way to showcase JSON data using jQuery AJAX?

Here is my AJAX request: $(".colorme").on("click", function () { var c = $(this); var b = "id=" + c.attr("id"); $.ajax({ type: "POST", url: "../../colorme", data: b, success: function (a) { ...

Showing data from the POST request in a dialog box

Greetings to all! I am in the process of building a webpage to test my API. The goal is to send a form to my nodejs backend and receive a JSON response back. So far, sending the request is functioning properly and I can track its progress on my VPS conso ...

My data is not appearing with ng-repeat or ng-bind

One issue I am encountering is that my ng-repeat / ng-bind is not displaying the data within $scope.articles, even though I am getting the expected data in the console. To help identify the problem more easily, I have created a code snippet below: var A ...

Avoiding HTML Encoded Characters when sending button or form submissions

When a user clicks a button that uses the GET method, I need to send multiple values at once. To achieve this, I am using an argument in the following way: $argument='var2=value2&var3=value3'; echo "<button value='value1&$argument ...

Utilize JQuery to target all elements except for those within a specified excluded class

I am looking to target all elements within a container that has the class DnnModule-efforityEaloHTML var all = $(".DnnModule-efforityEaloHTML *") <== This method is effective However, I now want to exclude any items with the class nostrip I have atte ...

Template for Vue.js Component Registration

Below is a simple Vue component example: const MyComponent = Vue.component('my-component', { data () { // data here... }, methods: { // methods here... }, template: '<p>Hello, world !!!</p>' }); I ...

Establish communication between two Sails applications

I am currently working on a Sails.js project that features a member portal with all possible routes and actions. However, I am considering developing a CMS using Sails as well. Originally, my plan was to integrate the CMS into the existing project, but n ...

Enhanced Firefox functionality with support for multiple columns

It has come to my attention that Internet Explorer 9 and older versions do not support multiple columns. However, even with the latest version of Firefox, I am experiencing issues with this website loading correctly. Do you have any insight into what might ...

resolved after a new promise returned nothing (console.log will output undefined)

Here is my Promise Function that iterates through each blob in Azure BlobStorage and reads each blob. The console.log(download) displays the values as JSON. However, when trying to close the new Promise function, I want the resolve function to return the ...

Struggling to align a search box with other items in a custom navbar using Bootstrap 4?

I created a unique navigation bar using Bootstrap 4's grid system. The navbar is designed with two sections: one for the navigation items on the left and another for the search box on the right. Unfortunately, I am facing an issue where the search box ...