What could be causing media queries to not update values even after being changed through JavaScript?

I have a simple navigation bar on my website, featuring links to different subpages. To enhance the user experience on mobile devices, I added a hamburger menu icon that is displayed on smaller screens. The links in the navigation bar are hidden using CSS media queries by setting their font-size to zero. When the menu icon is clicked, a JavaScript function is triggered to adjust the font size of the links accordingly.

Everything seems to be working smoothly with this setup, except for one issue. Upon resizing the browser window after the font sizes of the links have been altered by the script, those changes persist and do not revert back to the original values defined in the media query. This results in either extremely large or invisible fonts depending on whether the mobile menu was open or closed. Why aren't these font size values being reset when resizing the browser back to full-screen?

Here is a code snippet that includes the necessary code to replicate the scenario:

var open = false;

function openmobilemenu() {
    var nav = document.getElementsByTagName("nav");
    var links = nav[0].getElementsByTagName("li");
    if (!open) {
        for (var i = 0; i < links.length; i++) {
            links[i].style.transition = "0.5s";
            links[i].style.fontSize = "10vw";
        }
        open = true;
    }
    else {
        for (var i = 0; i < links.length; i++) {
            links[i].style.fontSize = "0";
        }
        open = false;
    }
}
header {
    position: relative;
    width: 100%;
    height: 200px;
    background-image: url("../img/header.png");
    background-repeat: no-repeat;
    background-position: right;
    background-size: auto 100%;
    background-color: #CDCCCA;
}

    header img {
        position: absolute;
        width: 500px;
        padding: 0 15%;
        bottom: 10px;
    }

.mobilemenu {
    display: none;
}



nav {
    position: relative;
    background-color: #61625B;
    width: 100%;
    height: 100px;
}

    nav ul {
        position: absolute;
        bottom: 0;
        width: 70%;
        list-style: none;
        padding: 0 15%;
        display: flex;
        margin: 0;
    }

    nav li {
        width: 125px;
        text-align: center;
        transition: none;
    }

.navunderline {
    width: 125px;
    height: 0;
    margin: 5px 0 0 0;
    background-color: #DAD9D7;
    transition: 500ms;
}

nav a {
    color: #DAD9D7;
}

    nav a:hover {
        text-decoration: none;
    }

nav li:hover .navunderline {
    height: 5px;
    margin: 0;
}


@media screen and (max-width: 800px), (hover:none) {

    .mobilemenu {
        display: flex;
        color: #61625B;
        font-size: 100px;
        margin: auto 5%;
    }

        .mobilemenu a, a:hover, a:active {
            text-decoration: none;
        }



    nav {
        position: relative;
        background-color: #61625B;
        width: 100%;
        min-height: 10px;
        height: auto;
        overflow: visible;
        padding: 0;
        margin: 0;
    }

        nav ul {
            position: relative;
            height: auto;
            bottom: 0;
            width: 100%;
            list-style: none;
            flex-direction: column;
            padding: 0;
        }

        nav li {
            width: 100%;
            text-align: center;
            margin: 0;
            padding: 0;
            font-size: 0;
            height: auto;
        }

            nav li:hover {
                background-color: #8b131f;
            }

    .navunderline {
        display: none;
    }
 <head>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

 
 <header>
        <a href="index.html"><img src="img/logo.png" alt="some alt" /></a>
        <a href="javascript:void(0);" class="mobilemenu" onclick="openmobilemenu()">
            <i class="fa fa-bars"></i>
        </a>
    </header>
    
    <nav>
        <ul>
            <li><a href="content/unternehmen.html">Unternehmen</a><div class="navunderline"></div></li>
            <li><a href="content/leistungen.html">Leistungen</a><div class="navunderline"></div></li>
            <li><a href="content/referenzen.html">Referenzen</a><div class="navunderline"></div></li>
            <li><a href="content/news.html">News</a><div class="navunderline"></div></li>
            <li><a href="content/kontakt.html">Kontakt</a><div class="navunderline"></div></li>
        </ul>
    </nav>

Answer №1

The reason for this is that your JavaScript code is applying inline styles to the elements, and inline styles always take precedence over styles defined in your stylesheet.

To address this issue, you have three options:

  1. Use JavaScript to remove these inline styles on window resize events.
  2. Avoid using inline styles altogether; instead, apply or remove classes to these elements during resizing. Let your stylesheet handle the styling of these elements.
  3. Incorporate !important into the font styles within your stylesheet, although this method should be used sparingly as it can lead to specificity issues (not recommended).

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

Ways to obtain parameter from URL in Express without diving into the request object

const express = require('express'); const app = express(); app.use('/', anyroute); // in anyroute file router.route('/:id').get(controlFunction) controlFunction(req, res, res)=> { // Here we can get the "id" fr ...

Issue with nivo-lightbox not opening upon clicking image

I have diligently followed the instructions to set up this JavaScript plugin, but unfortunately it doesn't seem to be functioning properly. The plugin I'm using can be found here: All the links to the CSS, theme, and JavaScript files are display ...

Having trouble displaying DIV Content with CSS through printing

<script type="text/javascript"> function PrintElem(elem) { Popup($(elem).html()); } function Popup(data) { var mywindow = window.open('', 'mydiv', 'height=550,width=750'); mywindow.doc ...

Efficiently handling jsonwebtoken errors in node and express

Here is the verification function I've created: exports.verifyToken = function(req, res, next){ var token = req.body.token; jwt.verify(token, config.sessionSecret, function(err, decoded) { if(err){ return next(err); }else{ ...

Display drop-down item when selected for the first time and hide it when selected for the same item for the second time

Is there a way to display form input when "C" is selected and hide it when "A", "B", or "D" are selected? If "C" is selected again after initially showing the form input, should it be hidden? For example, if "C" is selected for the first time, the form inp ...

Height of VUE Carousel 3D Slider dimension

I recently integrated the VUE Carousel 3D Slider on my website, but I'm facing an issue with controlling the height of the slides. There seems to be excessive space below the slider because the slides are unnecessarily tall. I attempted to adjust the ...

Parsing JSON data repeatedly using JavaScript within an HTML environment

The following code I found on a popular web development website works perfectly: <!DOCTYPE html> <html> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url ...

Detach attention from TextField select component in Material UI and React through manual means

When I create a select input using the TextField component from Material-UI library, I need to manually remove focus after an option is selected. I attempted to achieve this by using a reference to the TextField with the 'inputRef' prop. However, ...

Enhancing the capabilities of a browser detection function in Javascript

Looking to enhance my Javascript browser detection function with input from others. Concerns: The assumption that "Chrome 18" is equivalent to "Maxthon 3" may not be accurate! How can we distinguish between Chrome 18 and Maxthon 3? Similarly, how can we ...

JavaScript code does not seem to be functioning properly on my computer, but it works perfectly fine on

While the code functions perfectly in JSFiddle, it seems to fail when I try to implement it in an HTML file. Despite my efforts, I am unable to pinpoint the source of the issue. If you'd like to view the working version, here is the Fiddle demo. Bel ...

JavaScript: create a button that dynamically changes size and color when scrolling

I have a pulsing button (#scrollarrow) at the bottom of my website that disappears as I start scrolling. The jQuery code responsible for this effect is as follows: $(document).ready(function(){ $(window).scroll(function(){ if ($(thi ...

Typescript - type assertion does not throw an error for an invalid value

When assigning a boolean for the key, I have to use a type assertion for the variable 'day' to avoid any errors. I don't simply do const day: Day = 2 because the value I receive is a string (dynamic value), and a type assertion is necessary ...

Struggling to display the inline navbar

For the past few hours (a little over 3 hours, to be exact), I've been grappling with an issue that seems fairly simple. Despite scouring through various SO posts and other resources, I just can't seem to figure out the problem. The crux of the ...

receiving unexpected data while using AJAX

For my PHP project, I have a function that validates a textbox using AJAX. The AJAX is working fine, but it only gives the following output for $return_value==-4 "<br /> <font size='1'><table class='xdebug-error xe-deprecated ...

I keep encountering an issue when trying to load the website <a href="linktext.com">linktext.com</a> using SQL and PHP

I recently encountered an issue while trying to retrieve data from an SQL database on a webpage using PHP. The process was interrupted whenever there was a hyperlink present in the SQL text data, such as linktext.com. I attempted to use HTML special chara ...

Tips for relocating a div panel below all other div panels when a button is clicked with JQuery and CSS

There are several panels stacked below each other. Each panel has a button that, when clicked by the user, should move the panel to the bottom of the stack. For example: If there are 10 panels aligned sequentially and the user wants to remove Panel 2 by ...

Require field change in SharePoint 2010

I have implemented the following code on a SharePoint page - it locates the specified select based on its title and triggers an alert when the "Decision" value is selected. I am interested in removing the alert and instead substituting with code that iden ...

Styling with CSS to accentuate the currently active tabs

Struggling with writing CSS to meet the following requirements after creating a tab and calling a function on click: 1. The active tab should display a blue underline color. 2. When clicking on a tab, the blue line should appear under the active tab (sim ...

Learn how to create a stunning effect by combining two half images and revealing a full image upon hover with a smooth animation

I am struggling with implementing a specific feature using jQuery. I have designed a page hero with two sections (red and black): My goal is to have the black section expand over the red section when hovering, creating a full black box. I want the same ef ...

Leveraging the outcome of an API request with Protractor

I have developed a small API that generates test data instantly. Each request creates a new user and provides the relevant data. For fetching the data, I utilize the 'request' package: var flow = protractor.promise.controlFlow(); var result = f ...