Issue with menu height persisting while resizing screen

For my responsive design project, I am implementing a menu that switches to a menu button when the width is less than or equal to 768px.

Currently, I am using jQuery to dynamically adjust the height of the menu when the menu button is clicked. The jQuery script adds style="height: 152px;" to the nav element, while CSS3 with

transition: height 0.35s ease 0s;
ensures smooth sliding animation.

Everything works smoothly until I resize the window while the menu is displayed. When the width > 768px, the menu items are floated horizontally on the same line instead of stacking vertically below each other.

The issue arises from the fact that even though the menu is no longer needed, it maintains a height of 152px, creating unnecessary space below it.

I have attempted to find a listener that can detect when the menu button becomes hidden (display: none;) so that I can remove the inline style, but so far, I have not been successful.

If anyone has a straightforward solution to this problem, any help would be greatly appreciated.

Here is a link to my fiddle

// CSS
.nav-collapse {
  overflow: hidden;
  transition: height 0.35s ease 0s;
}

@media (max-width: 768px){
  .collapse { height:0; }
}

// JS
$('.btn-navbar').click(function(){
var nav = $('.nav-collapse');

if($(nav).hasClass('collapse')){
$(nav).height($(nav).find('ul').height());
$(nav).removeClass('collapse');
} else {
$(nav).attr('style','');
$(nav).addClass('collapse');
}
});

// HTML
<nav class="nav-collapse collapse">
  <ul>
    <li> menu items </li>
  </ul>
</nav>

Answer №1

To achieve the desired behavior of the menu uncollapsing itself when the viewport increases in size and having the height automatically calculated by the browser, you can simply listen to the window resize event and take appropriate action if the screen size exceeds a certain threshold (in this case, set at 600px in your fiddle):

$w.resize(function () {
    // Uncollapse navigation when viewport gets bigger
    if ($w.width() > 600) {
        $nav.css({
            height: "auto"    // Adjusts nav height to auto
        });
    }
});

It is recommended to declare the $nav variable earlier in the code for better organization, like in this example:

var $nav = $('.nav-collapse'), // Using $var for objects to maintain clarity
    $w = $(window),            // The $(window) object
    threshold = 600;            // Define the threshold value

// Listen for click event
$('.btn-navbar').click(function () {

    // Modify $(nav) to $nav for consistency
    if ($nav.hasClass('collapse')) {
        $nav.height($nav.find('ul').height()); // Necessary for transition effect
        $nav.removeClass('collapse');
    } else {
        $nav.attr('style', ''); // Needed for transition effect
        $nav.addClass('collapse');
    }
});

// Listen for resize event
$w.resize(function () {
    // Uncollapse navigation when viewport gets bigger
    if ($w.width() > threshold) {
        $nav.css({
            height: "auto"    // Adjusts nav height to auto
        });
    }
});

Answer №2

Avoid directly setting the height using inline styles. Instead, utilize jQuery to assign a class that specifies the desired height, ensuring that this class only takes effect within the max-width: 768px media query. When this media query is no longer in use, the fixed height will no longer be enforced.

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

Storing information in a database using Ajax in the Yii Framework

I am looking to extend the validity of a specific post by updating its toDate field and adding 1 month. Initially, I display all available posts with a button beside each one that, when clicked, triggers the update process. In the code snippet below, clic ...

Using Page.ResolveClientUrl in JavaScript or jQuery allows for easy resolution of client

I find myself in a predicament where I need to choose between using an HTML page instead of a .aspx page for performance reasons. Currently, I am using an aspx page solely because of the CSS and javascript file paths like: <script type="text/javascript ...

Creating CSS styles for fluid width divs with equal height and background images

Looking to create a layout with two side-by-side divs of equal width - one containing an image and the other dynamic text that can vary in height from 400px to 550px based on input. The goal is for the image to align flush at the top and bottom with the te ...

The min-height property in CSS appears to be ineffective on Jelly Bean

In my current project developing an Android application, I have incorporated Webviews in certain activities and fragments. However, I encountered a perplexing issue when running the app on Jelly Bean (api 16 and 18) emulator - the css property min-height ...

Modifying attributes for individual components in Vue.js classes

Recently, I integrated a reusable component called "LightBox" into my website, which displays images in higher resolution. The LightBox functionality is linked to each element having a thumbnail. However, I encountered an issue. There are multiple elements ...

Interactive JavaScript Slider for Customizing Selection

Recently, I came across a range slider and I am trying to make it more dynamic. The current JavaScript code has hardcoded references to specific HTML elements, and I want to have multiple sliders on my HTML page, each functioning independently. The code sn ...

ReactStrap: Transparency issue with DropDown items on mobile devices

I've encountered an issue with my dropdown menu that works perfectly on desktop: https://i.sstatic.net/73Z0X.png However, on mobile devices, it appears to be transparent for some reason: https://i.sstatic.net/dhtOw.png Here is the code snippet ...

Have you ever wondered how to disable a tooltip in React Material UI after clicking on it? Let

I am working with a Material-UI tab component and I would like to include a tooltip feature. The issue I am facing is that the tooltip does not disappear when I click on the tab. It should hide after clicking on the tab. Currently, the tooltip remains vi ...

Need help with styling for disabled autocomplete? Check out the attached image

I'm currently working with material-ui and react to create a basic form. Everything is functioning properly except for a small UI issue that I can't seem to figure out how to resolve. When I utilize the browser's auto-complete feature, the i ...

How to Use JQuery to Identify Duplicate IDs in a JSON Array

Here is a JSON array: [{ "Id": "1", "Name": "A" }, { "Id": "2", "Name": "B" }, { "Id": "3", "Name": "C" }, { "Id": "4", "Name": "B" }, { "Id": "5", "Name": "D" }, { "Id": "6", "Name": "E" }, { "Id": "7", ...

HTML TABS: Make the first TAB automatically selected

I've been experimenting with tabbing in HTML using a tutorial I found on W3SCHOOLS. While the source code provided works fine, I'm encountering an issue with automatically selecting the first tab by default. The tutorial doesn't cover this, ...

Inserting a crisp white divider between items in breadcrumb navigation in the form of arrowheads

I have designed a unique custom breadcrumb with an arrow shape : <ol class="breadcrumb-arrow"> <li class="active"><a href="#">1. Foo<span class="arrow"></span></a> </li> <li ...

Combining PHP JQuery Dialog with Datatables results in a sleek design loss

Recently, I encountered an issue with my code. I have a file called incident_view.php which pulls data from the database and displays it using Datatables. Everything was working fine until I tried to open this page in a JQuery dialog on another page called ...

Dynamic header following the scroll position

I'm experiencing an issue where my background moves with the scrollbar, causing the header of the page to scroll along. I've included my code and a screenshot for reference. Any assistance would be greatly appreciated. Thank you. Here's my ...

What is the most recommended jQuery version to utilize?

My goal is to change a selected button (buttons = .answerBtns) to an unselected button whenever the option in the OptionDropId drop down menu changes. Below is the jQuery code for drop down menus: $(document).ready(function () { var OptDrop = new Arr ...

What could be causing the span class data to not be retrieved by the getText method

Looking to retrieve the value of a span class called 'spacer-right big project-card-measure-secondary-info' <span class="spacer-right big project-card-measure-secondary-info">1</span> snippet of code: browser.waitForEl ...

Customize and format the text of options in a select element using the jQuery Chosen plugin

I have been exploring the jQuery plugin chosen for a select box with autocomplete functionality. You can check it out here: Does anyone know how to customize the appearance of the text in the options of the select box? Is there a specific method within t ...

Run the js.erb code only when a certain condition is met

I'm feeling a bit lost when it comes to CoffeeScript and JS. I have a quick editing feature that sends an AJAX request and updates the database. Currently, I manually change the edited content's place and display it, but it feels like a workaroun ...

Modifying CSS stylesheet does not alter the background color

body { background-color: bisque; } <!DOCTYPE html> <html> <head> <title>Reading</title> </head> <body> <h1> <button><a href="index.html">Home</a></button> & ...

Creating a standalone static page in Wordpress showcasing the header, sidebar, and footer of the twenty fourteen template

I have created a static blank page containing my website's header, sidebar, and footer. However, I am trying to remove the 'style' that is being enforced by the CSS of my WordPress template on the page. Below is the code I am using: <?p ...