Modify the CSS styles (which were set by a preceding function) upon resizing the screen using Javascript

In the mobile version of a website (width less than 620px), there is a button in the header. Clicking this button triggers the "mobileNav" function, which toggles the visibility of the mobile navigation between "display: none;" and "display: flex;". This functionality works well! However, a problem arises when the menu is opened at a screen width below 620px and then the screen size is increased; the mobile nav remains visible and cannot be closed due to design constraints.

A solution is needed to either revert the button back to its initial state ("Off") or override the styles that were applied by clicking the button when the screen size is increased. For instance, if clicking the button sets #mobile-nav to "display: flex;", resizing the screen should change it back to "display: none;".

Below is a code snippet with some messy CSS, but the key points are:

  • "mobile-nav" is hidden on desktop screens
  • "desktop-nav" is hidden on mobile screens
  • The "mobileNav" function toggles "#mobile-nav" visibility when the button is clicked
  • Currently, the "mobileNav" function does not close the mobile navigation when the screen is resized

Here is a simplified version of the JavaScript function responsible for this behavior:

// Mobile Navigation Function--------------------------------

function mobileNav() {
    // Rotate Burger One and Reposition
    var x = document.getElementById("burger-one");
    if (x.style.transform === "rotate(45deg)") {
        x.style.transform = "rotate(0deg)";
    } else {
        x.style.transform = "rotate(45deg)";
    }

    // Rotate Burger Two and Reposition
    var y = document.getElementById("burger-two");
    if (y.style.transform === "rotate(-45deg)") {
        y.style.transform = "rotate(0deg)";
    } else {
        y.style.transform = "rotate(-45deg)";
    }

    // Toggle Mobile Nav Display
    var z = document.getElementById("mobile-nav");
    if (z.style.display === "flex") {
        z.style.display = "none";
    } else {
        z.style.display = "flex";
    }
}

// Rest of the script goes here...

Answer №1

Here's a quick solution...

Do you want the mobile menu to be hidden when the resize event is triggered?

This might also happen when switching between portrait and landscape mode... but it could still be helpful. The decision is up to you.

window.addEventListener("resize", ()=>{
  if(document.getElementById("mobile-nav").style.display === "flex"){

    // Call the existing function to close the menu
    mobileNav();
  }
});

Check out the CodePen example for reference

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

Converting Latin numbers to Arabic using PHP

Looking for a way to convert English numbers to Arabic within specific elements in an HTML page using PHP? Here's my attempt at some code, but it ends up converting all numbers in the page. I only want to convert numbers between certain elements. Any ...

Steps for positioning an element to the left and center of a div

I'm having trouble aligning my two elements in a simple horizontal menu to the middle left. I want them to have a margin of 5px on the left and right sides. Here is a screenshot and CSS style: https://i.stack.imgur.com/vzO5D.png .body_clr { wid ...

Click on a specific image in a table using Cypress with a specific source URL

I need help with a query for Cypress regarding a table of items, each item having active (blue) and not active (black) images. How can I set up this query? Below is an image of the table list: https://i.stack.imgur.com/74qzb.png And here is the HTML code ...

What is the best way to retrieve the local image path, transform it into a File object, and subsequently transfer it to firebase?

My current form includes a signup option where users can choose to upload a profile picture. In case they do not upload a profile picture, I aim to use a default one (think of the default Facebook profile picture). The image is imported as: import defaul ...

What is the method in HTML to resize an image in just one direction?

Imagine this scenario: I need to fit a 10x60 image into a 15x15 container. The goal is to stretch the image width proportionally (resulting in a 15x90 image), but without stretching the height beyond the width, which would cut off the bottom of the image. ...

Tips for making a sidebar sticky when scrolling

In order to keep the right-side bar fixed, I have implemented this javaScript function: <script type="text/javascript> $(document).ready(function () { var top = $('#rightsidebar-wrapper').offset().top - parseFloat($('#rightsideb ...

Refreshing JSON data every 10 seconds using SVG/D3

What is the best way to program a D3/json/ajax query that retrieves new data every 10 seconds? Here is my initial attempt at a solution, but I believe it may not be ideal: setInterval(function() { d3.json("http://1.....", function(json) { .... }) ...

Tips for concealing a Div in an HTML document with the help of Angular

I need a solution to hide a div that contains only titles, while the div with the actual content is located in a different section <div> <b>Delivery Info\</b> <div class="custom-control">Delivery ID: </div ...

Steps for releasing a third-party library that is compatible with both Angular 2 and Angular 4

Currently, I am utilizing a third-party library for Angular that is compatible with Angular 2. However, I want to make sure this library can support all versions of Angular, including Angular 4 and Angular 5. How can I go about publishing an updated vers ...

The GM_xmlHttpRequest POST method is not functioning properly when called within an event listener

My simple goal is to intercept xmlHttpRequests sent by a page and send them to my local server for logging in a text file. However, Ajax calls do not work in event listeners. I have tried various solutions all day long without success. Here is the code sni ...

Achieve perfect alignment of Bootstrap checkboxes

Is there a way to vertically align checkboxes in a column with their labels? My goal is to have these elements centered on the page, but I want the checkboxes themselves to be aligned vertically. <div class="row"> <div class="span12 paginatio ...

Getting the nth-child rule for CSS in IE9 to function properly in IE8

This code is functioning in IE9: body.country-XYZ .abc:nth-child(3) { display:none; } As :nth-child() is effective in IE9 and newer versions, what can be done to ensure it also functions on IE8? Can you suggest an alternative method for achieving th ...

The words overlaid on the image spill out beyond its edges

I want to create a design where the text flows outside of the image and continues into another container. After some trial and error, I managed to achieve a layout where the text seamlessly extends beyond the image and into a separate section. Ideally, the ...

Ways to prompt the debugger to pause whenever a specific script file is called during execution in Edge/Chrome debugger

I am currently in the process of debugging a Typescript web application, which is quite new to me as I have never delved into web development before. This particular project entails multiple script files and various libraries. While running the applicatio ...

When the overflow is set to visible, the background color vanishes

Here is the CSS code I have written; #container { width: 1300px; background-color:green; margin:0 auto; overflow:hidden; } #menu { float:left; width:20%; background-color: yellow; } Even after extensive searching on Google, I ...

Convert HTML tables from Yahoo Pipes into an array of JSON objects

Currently, I am experimenting with Yahoo Pipes in an attempt to convert multiple tables within a DIV into an array of JSON objects. At the moment, the HTML is being successfully parsed. Here is my current setup on Yahoo Pipes I envision each table cell ...

Creating an HTML table layout: A step-by-step guide

I am in need of assistance with designing an HTML layout. My goal is to display 3 columns for each table row as described below: Column #1 will contain text only. Column #2 will have an inner table, which may consist of 1 or 2 rows depending on the cont ...

Utilizing a linked list to manage consecutive JS/Ajax/Jquery requests for seamless processing

Here is my code snippet: <script type="text/javascript"> var x = 1; var data = JSON.parse( document.getElementById('json').innerHTML); var next = data['next']; var jsonData = data['data']; ...

What is the method for mocking a function that returns an HTTP response?

My current project involves working with ExpressJS and I'm facing a challenge in stubbing a function that returns an HTTP response within a router. Specifically, I need to mock a request to Amazon S3. app.get('/', (req, res, next) => { ...

Is there a way to customize the Webpack output to incorporate specific options solely for a particular bundle?

Currently, I am using Webpack 4 to build multiple bundles. My requirement is to add the output options libraryTarget and library for a single bundle only. The default configuration looks like this: output: { path: path.resolve(__dirname, 'dist/j ...