JavaScript does not recognize external styles (when an if statement is involved)

I recently started learning web development, and I encountered an issue while working on a responsive design project. When the hamburger menu is clicked, the lines for expansion that are defined in an external CSS file are not being detected. Instead, new inline styles are created by JavaScript, which then allows it to work as expected. HTML:

<nav class="mobileNav" id="mobileMenu">
    <a class="mol-6" onclick="show();" href="index.html">
        <figure>
            <img class="icon" src="images/nav/home.png" alt="">
            <figcaption>Home</figcaption>
        </figure>
    </a>
    <a class="mol-6" onclick="show();" href="astronomy.html">
        <figure>
            <img class="icon" src="images/nav/astro.png" alt="">
            <figcaption>Astronomy</figcaption>
        </figure>
    </a>
    <a class="mol-6" onclick="show();" href="telescope.html">
        <figure>
            <img class="icon" src="images/nav/tele.png" alt="">
            <figcaption>Telescopes</figcaption>
        </figure>
    </a>
    <a class="mol-6" onclick="show();" href="about.html">
        <figure>
            <img class="icon" src="images/nav/about.png" alt="">
            <figcaption>About</figcaption>
        </figure>
    </a>
</nav>

CSS:

#mobileMenu {
 font-family: light, sans-serif;
 max-height: 0px;
 z-index: 99;
 transform: translateY(-100%);
 overflow: hidden;
 padding: 0px;
 transition: transform 0.5s;
}

Javascript:

function show() {
if (document.getElementById("mobileMenu").style.maxHeight == "0px") {
    setTimeout(function(){
        document.getElementById("mobileMenu").style.maxHeight = "100%";
        document.getElementById("mobileMenu").style.position = "fixed";
        document.getElementById("mobileMenu").style.padding = "1%";
    }, 1)
    document.getElementById("mobileMenu").style.transform = "translateY(0px)";
} else {
    setTimeout(function(){
        document.getElementById("mobileMenu").style.maxHeight = "0px";
        document.getElementById("mobileMenu").style.padding = "0px";
        document.getElementById("mobileMenu").style.position = "relative";
    }, 500)
    document.getElementById("mobileMenu").style.transform = "translateY(-100%)";
}}

Working Example: Astromuneeb (Require Portrait Orientation)

Your assistance with this issue would be greatly appreciated.

Answer №1

Exploring alternative methods could enhance the outcome you're aiming for. One suggestion is to utilize css classes for styling and reserve javascript solely for toggling classes.

Answer №2

I share the same opinion as Eugene, however, it seems like the .mobileNav class is taking precedence over your portrait media query.

https://i.sstatic.net/9qn5R.png

I included !important in your .mobileNav portrait media query but it still doesn't override it; I assume it has something to do with the hierarchy. It's strange that you're getting display:none; as an inline style on your nav when opening and closing it currently, which won't be helpful.

Following Eugene's suggestion, it would be best to simply set an .open class and use CSS transforms for the animation. Just add or remove the class on the nav accordingly.

When using media queries in CSS for mobile devices, it's probably better to specify screen sizes first and consider starting with styling for mobile screens...

.mobileNav { display: block; }

@media (min-width: 992px) {
  .mobileNav { display: none; }
}

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

Creating a dynamic dashed line animation using SVG

Imagine a line growing in the same pattern as this fiddle. svg #path { stroke-dasharray: 19; stroke-dashoffset: 19; animation: dash 4s linear 0s forwards; } @keyframes dash { from { stroke-dashoffset: 19; } to { ...

Navigating to a different directory using Node.js and ExpressJS route mapping

I'm struggling with setting up routing using ui.router. This is the structure of my folders: https://i.stack.imgur.com/Fu0A9.png In the app.js file within the javascripts folder, I have the following code: var app = angular.module('testing&ap ...

The fixed navigation bar shows a flickering effect while scrolling at a slow pace

Currently facing a challenge with our sticky navigation. Noticing a flickering issue on the second navigation (sticky nav) when users scroll down slowly. The problem seems to be specific to Chrome and Edge, as it doesn't occur on Firefox, IE11, and S ...

I am having trouble getting the auto refresh feature in the div to work properly

As a newcomer to PHP and Javascript, I am trying to create a div that contains an ads script and refreshes every minute. I believe I have everything set up correctly in my code: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ lib ...

LinkButton not triggering on Master Page when accessed from Second Child Page in ASP.NET

I am currently working on a project in ASP.NET (Framework 4.0) where I have implemented an Asp LinkButton in the Master Page that is linked to two different pages (Home.aspx and service.aspx). The question at hand is: The LinkButton1 functions properly on ...

React - Unable to perform 'removeChild' on 'Node' object: The specified node cannot be removed as it is not a child of this node

I am encountering an issue in my React project with the following structure: <div className="App"> <BrowserRouter> <BasicLayout title={"test"}> <Routes> <Route path="/home&qu ...

What are the implications of utilizing a query string in a POST request?

In our system, POST requests are sent from the frontend to the backend. Instead of using the body to pass data to the server, these requests utilize query strings in the URL params. It is important to note that these requests only contain string parameter ...

Including a drop-down arrow or triangle next to the initial button

In the navigation bar displayed below https://codepen.io/shaswat/pen/XzpRXL Is it possible to create a down triangle or arrow next to the "home" link, which changes direction upward when hovered over? How can this be achieved without modifying any HTML e ...

Mutating properties in VueJs

When I attempted to move a section for filtering from the parent component to a child component, I encountered this error message: "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a ...

I have expanded the CSSStyleDeclaration prototype, how do I access the 'parent' property?

I have developed some custom methods for CSSStyleDeclaration and implement them like this: A_OBJECT.style.method() ; The code structure is quite simple: CSSStyleDeclaration.prototype.method = function () { x = this.left; ..... etc } Here's my que ...

What steps should I take to include a Follow - Unfollow Button on my Website?

I need to add a button on my website that allows users to either follow or unfollow a specific game. Here is the table for the follow buttons: Follow Button Table When a user clicks on the button related to the game ID, it should update the game_follow d ...

Nested arrays in the JavaScript programming language

Is this JavaScript code accurate: var options = []; options.push(["Tom","Smith"]); options.push(["Mary","Jones"]); where each item in options is a two-element array of strings. I plan to add items to options using a for loop. Furthermore, can I i ...

Should I use React with Spring Boot or just Spring Boot for this project?

My partner and I are collaborating on a project for our current semester course. As we delve into our research on potential technologies to use, it seems like Spring Boot for the server side along with MySQL or Postgres for the database are emerging as s ...

Unable to change data in table TD using AJAX and PHP received JSON array

I am currently facing an issue with a PHP-AJAX script that is responsible for deleting financial rows from a table. The PHP script is functioning correctly and successfully deleting the rows. However, the problem arises within the success function of the A ...

Tips on refreshing the D3 SVG element following updates to the dataset state in a React application

Hey everyone, I'm currently experimenting with D3.js and React in an attempt to build a dynamic dancing bargraph. Can anyone provide guidance on how to reload the D3 svg after updating the dataset state within REACT? Feel free to check out my codepen ...

How come my fixed navigation bar is appearing above my sticky navigation bar even though I positioned it at the bottom in the code?

My current project involves creating a sticky bar and fixed navbar using Bootstrap 5. I structured my code with one file for the sticky navbar and another file for the fixed navbar. The challenge I faced was having the fixed navbar overlap the sticky navba ...

A snippet of jQuery programming that enables automatic transitions between images

Trying to figure out how to achieve this - I want an image to change every 3 seconds using jquery. Can anyone help me with this? Unfortunately, I haven't been able to find any resources on this specific topic. ...

The functionality of tinymce setContent can only be activated by directly clicking on it

Everything is running smoothly with the code below: $('.atitle').on('click', function(){ console.log('323'); tinymce.get("ed").setContent("<p>lorem ipsum</p>"); // it's working ...

Error message: "Uncaught TypeError: Cannot read property 'module' of undefined when using AngularJS in conjunction with RequireJS."

Embarking on my journey of app development with angularJS was a thrilling experience. However, after investing weeks into the project, I had an epiphany - why didn't I start using require JS from the get-go to load my modules? A rookie mistake, yes, b ...

How can we refresh the model in Angular.js from a section of the application that has not been 'angularized' yet?

UPDATE: Found a similar question at Call Angular JS from legacy code Working on adding a new feature to an existing application using Angular. Unable to do a complete rewrite, so the challenge is integrating Angular models with the rest of the app that di ...