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

What is the best way to access the child DOM of a Vue element?

Is there a way to access the child DOM element of a Vue component? In the code snippet below, I am trying to retrieve the <input> element nested within the <div>. var vm = new Vue({ el: '#box', data: { pick: true, a: & ...

Struggling to integrate buttons into an h2 element with the use of createElement() and appendChild() in HTML/CSS/JS

As I work on developing a website, one of the features I've been implementing is the ability for users to add books to a list and then review or delete them. The process was smooth sailing until I reached the point of adding buttons for these actions. ...

Facing unexpected behavior with rxjs merge in angular5

import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/merge'; this.data = this.itemsCollection.valueChanges() this.foo = this.afs.collection<Item>('products') .doc('G2loKLqNQJUQIsDmzSNahlopOyk ...

Having trouble using jQuery's .off() method to remove an event handler?

I'm facing an issue with my jQuery code where the .off('click') method doesn't seem to be working. I've tried removing the event binding from '.reveal-menu', but it's not working as expected. The initial animation wo ...

Evaluating CSS Specificity

Is there a recommended approach for automatically testing css selectors? I am in the process of developing a SCSS framework and I want to integrate automated tests. Specifically, I aim to verify that the css selectors are functioning correctly. For examp ...

Create a dynamic form using JSON data and the Material UI library

Looking for assistance in creating a dynamic form on Next.js by parsing JSON files and generating the required components from the JSON data. Additionally, seeking guidance on utilizing the Material UI library for styling. Any examples or help would be g ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

Caution: PHP's move_uploaded_file() function is unable to successfully relocate the audio file

I've implemented a straightforward Record Wave script using Recorder.js Encountering an Issue Recording works fine Playback of my recording is successful Downloading the recorded file from blob works smoothly The problem arises when trying to uploa ...

Create a visual representation using a push button

Hey there, I'm attempting to create an image using a button on canvas. However, I'm facing an issue where I can't draw on the clear canvas. Here's my code: <!doctype html> <html> <head> <meta charset="utf-8"> ...

Display the background-image of the <body> element only when the image has finished loading

I have a webpage where I want to delay showing a large image until it has finished downloading. Instead, I would like to display a background with a fading effect while the image loads. The challenge is that the background image must be set within the bod ...

Issue with mapStateToProps not reflecting changes in props after localStorage modification

Currently, I am working on a redux application that involves authentication. My main concern right now is ensuring that the user remains logged in whenever they interact with the app. Below is a snippet from the bottom of my App.jsx file: function mapStat ...

Effectively encoding and decoding AJAX and JSON objects with PHP scripting

I've successfully set up a basic HTML file with a fixed JSON object. My goal is to transfer this object to a PHP file named text.php, encode it, decode it, display it in the PHP file, and then showcase it back in the HTML file. <!DOCTYPE html> ...

How can I download a PDF file in React.js using TypeScript on Next.js?

I've created a component to download a PDF file. The PDF file is named resumeroshan.pdf and it's located inside the Assets folder. "use client"; import resume from "/../../Assets/resumeroshan.pdf"; export default function Abo ...

Guide on implementing ES6 script's template literals

I've been tackling a template literal question on hackerrank. It's working smoothly on my local IDE, but encountering an error on the Hackerrank IDE. Here's the code to add two numbers and print the result using a template literal: const sum ...

Tips on anchoring a footer to the bottom of a webpage following a loop in PHP

After running a PHP file with some HTML, I noticed that the footer is not staying at the bottom of the page as intended. It seems to be overlapping with the products or leaving empty space after them due to changes in the DOM. If anyone has insight on how ...

Updating by clicking with auto-prediction feature

I have implemented an autosuggestion feature to display results from a database table while typing in an HTML field, and I am looking to utilize JavaScript to post another value from the same row where the autosuggested values are stored. https://i.stack. ...

What is the best way to transfer a JSON object from Java to JavaScript?

I've been struggling to pass data from my Spring controller to JavaScript, but I haven't had any success so far. Would using ajax be the best approach for this task? Can you provide me with some hints on how to achieve this effectively? In my co ...

Div sliding out of view

I'm encountering a slight issue with this template: essentially, my goal is to implement a feature where clicking on a box will expand it while simultaneously sliding the other boxes off-screen. However, instead of just sliding the div off-screen, it ...

python and html tutorial for adding text from bottom to top

Looking for help with rearranging lines in an HTML file? If you want the lines to be displayed in reverse order, here's an example: (1) (2) (3) You need them to appear like this: (3) (2) (1) try: record_cam.strHandler ...

Eslint in Gulp can't locate my .eslintrc configuration file

My gulp-eslint is unable to locate my .eslintrc file. I've set up a lint task as follows: gulp.task('lint', function () { gulp.src(['src/**/*.js', 'src/**/*.jsx']) .pipe(eslint()) .pipe(eslint.format()); }) The t ...