JavaScript triggering CSS animations to make elements flash and stand out

I am experiencing a peculiar issue with my mobile menu. It works smoothly when the window is resized to below 736px, and the toggle animation adds CSS classes to animate the menu in and out.

However, after resizing the window, opening and closing the mobile menu, and then resizing the window again to hit the media query breakpoint at 736px, the dropdown mobile menu flashes briefly before disappearing.

If anyone has encountered this problem before and can offer a solution, I would greatly appreciate it.

** Note that removing the mobileMenuActive class is not an option as I need the menu to animate out.

To see the code in action, visit: https://codepen.io/emilychews/pen/POeGaN

Here is the JavaScript code:

var mobileMenuButton = document.getElementById("mobile-menu-button")
var mobileMenuItems = document.getElementById("nav-menu-items")

// TOGGLE MOBILE MENU
var mobileMenu = false

function toggleMobileMenu() {

    if (mobileMenu === false) {

      mobileMenuItems.classList.remove("mobileMenuInactive")
      mobileMenuItems.classList.add("mobileMenuActive")
      mobileMenuButton.innerHTML = "Close"
      mobileMenu = true

    } else {

      mobileMenuItems.classList.add("mobileMenuInactive")
      mobileMenuItems.classList.remove("mobileMenuActive")
      mobileMenuButton.innerHTML = "Menu"
      mobileMenu = false

    }
}

mobileMenuButton.addEventListener("click", function() {
    toggleMobileMenu()
}, false)

And here is the CSS code:

body, ul {padding: 0; margin: 0}
...

Finally, here is the HTML code:

<header id="main-header">
  <nav id="main-navigation"> 
    <ul id="nav-menu-items">
      ...
    </ul>
    
    <div id="mobile-menu-button">Menu</div>

  </nav>
</header>

Answer №1

One solution is to utilize the resize event on the window and eliminate the mobileMenuInactive class. Then, your script reinstates it when "Menu" is clicked.

window.addEventListener('resize', function(){
    mobileMenuItems.classList.remove("mobileMenuInactive");
});

Answer №2

Give this JavaScript code a try:

var mobileMenuButton = document.getElementById("mobile-menu-button");
var mobileMenuItems = document.getElementById("nav-menu-items");

// TOGGLE MOBILE MENU
var mobileMenu = false;

function toggleMobileMenu() {

    if (mobileMenu === false) {
        mobileMenuItems.classList.add("mobileMenuActive");
        mobileMenuButton.innerHTML = "Close";
        mobileMenu = true;
    } else {
        mobileMenuItems.classList.remove("mobileMenuActive");
        mobileMenuButton.innerHTML = "Menu";
        mobileMenu = false;
    }

}

mobileMenuButton.addEventListener("click", function() {
    toggleMobileMenu();
}, false);

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

Implement a timer reset function with JavaScript on a click event

Here is the JavaScript code that I am working with: <script> $(document).ready(function () { window.setTimeout(function () { $('#logout_warning').reveal(); }, 6000) }); $(document).ready(function () { window.setTimeout( ...

Utilizing the push method to add a JavaScript object to an array may not be effective in specific scenarios

When I tried using users.push within the 'db.each' function in the code below, it didn't work. However, moving the 'users.push' outside of it seemed to do the trick. Is there a way to successfully push the new objects from db.each ...

Beyond the Realm of Three.js Skybox

Currently, I am developing a 3D game in JavaScript using three.js. Everything is going smoothly so far, however, one issue has arisen regarding the skybox not showing up when my camera's near and far distances are set too small. The problem stems fro ...

The v-model for a particular field is not reflecting real-time updates like the other fields with the same datatype. I'm trying to figure out what could be causing this issue

In my specific model, there are various values that can be updated through a form on the webpage. These values include "Quantity", "Rate", "Amount", "Net rate", and more. The problem I am facing is with binding these values with my inputs using v-model. E ...

Action outcome yielding identical content

Is there a way in MVC C# to return an ActionResult without making any changes to the view? I have attempted: Returning null and new EmptyResult(), but these result in an empty page Returning an empty JavaScript (again, resulting in an empty page) Retur ...

How can one use Selenium's XPath or CSS selectors to retrieve an element based on the text of its inner element or the text of the current element?

Exploring the code below: <section id="section2" class="MightChange1 MightChange2"> <div id="dynamicIdxxx" class="dynamic1 dynamic2 dynamic3"> <div id="againDynamic" ..> <div id="someDynamicCanBeRelayed" class="xyz"&g ...

How can I validate a password input in a form on click and reveal a hidden div on the same page without refreshing?

I've been attempting to create a password-only form that reveals a hidden div on the same page when the correct password is entered. I want to avoid reloading the page, but I'm unsure of how to achieve this. function checkPassword() { var co ...

Fluctuating price depending on the selected choice

Hello, I am in the process of updating the price based on the selection made from the options. I am unsure whether to use JavaScript or Ajax for this task and how to go about it. Can someone please guide me? <tr> <td width="160">Price:</td ...

Upon the initial toggle of the multilevelpushmenu, the hover trigger is activated

Currently, my website utilizes jQuery, Bootstrap, Font Awesome, Normalize, and jquery.multilevelpushmenu.js v2.1.4 to create a side-menu with multiple levels. I am attempting to implement a hover operation in conjunction with this menu, but encountering an ...

Looking to change the date format from 24/05/2021 to 24/May/2021 using jQuery or JavaScript?

My client prefers not to use a date picker, but wants to be able to type dates directly into a textbox and have them automatically converted to the format 24/May/2021 as they leave the field. I am looking for a solution using either Javascript or jQuery. ...

The order of event capturing and bubbling phases is FLIPPED for the node triggering the event

Note: Using Chrome, works as expected in Safari. In summary, I thought I had a good knowledge of JavaScript. To test my skills, I decided to take a challenge and guess what happened: We have an <input type="button" id="btn"> with two event handlers ...

Error Encountered: Invalid Parameter Type when Retrieving Item from AWS Dynamo

I've been facing issues when trying to establish a connection between my ReactJS application and AWS DynamoDB. Despite confirming the correctness of the API key, secret key, and region, I keep encountering an InvalidParameterType error. I have even at ...

Unlock the power of Font Awesome with the <i> </i> tag - Nibbler

I could use some assistance with a concept that I'm finding particularly challenging. After running my website through Nibbler, my goal is to achieve a perfect 10/10 score in all (or most) categories. However, I am facing difficulty due to the 17 in ...

Calculate the total of JSON objects while eliminating duplicates in an array

Below is an array of objects: const lineItems = [ { "lineNumber": "0", "item": "1496", "itemDesc": "wertyuiasdfghj", "qualityReceiptHold": "N", ...

Border concealed by Bootstrap Glyphicons

Is there a reason why glyphicons hide a border of a floated container? Can anyone shed light on this issue and suggest a workaround? Check out this link for more information. https://i.sstatic.net/CXZSd.jpg My setup: OS X 10.11.1, Chrome 47.0.2526.73 (6 ...

Switching from hover to click on the menu

I am struggling with adjusting the function to trigger on 'click' instead of 'hover'. I have attempted changing 'hover' to 'click' and using 'toggle' but have not seen any positive outcomes. $('#menu ...

Strategies for maintaining login status in Selenium

When utilizing selenium and bs4 to parse a webpage, I encounter an issue where the webpage requires scanning a QR code and entering a verification code to log in. To address this, I have implemented the use of WebDriverWait to pause the script until the u ...

What is the best way to ensure that bootstrap columns collapse in equal multiples?

I need to have 4 equal columns in each bootstrap row with only specific configurations allowed: All 4 next to each other Two above and two below All in a single column The issue is that when I adjust the screen size, sometimes I get 3 columns at the top ...

I'm struggling to figure out how to access deeply nested data from a JSON response in Reactjs. Whenever I attempt to access it, I keep getting hit with a frustrating TypeError

Currently in the process of learning react, I am experimenting with utilizing real-world APIs as a data source for my react application. One API I am working with provides a JSON response which you can see here. When attempting to access and use this da ...

Dynamic motion for the circular progress bar during initialization

Seeking assistance to animate the round progress bar border upon page load. Looking for animations for various percentage values. Any suggestions are greatly appreciated! Thank you in advance! For a similar animation example, click here. .progress-circ ...