Modify the background color of a pseudo-element's property value dynamically

How do I change the background color of my burger menu by clicking on an icon?

This is the CSS code I have:

:root{
       --pseudo-backgroundcolor: yellow;
    }
    .menu__icon span,
    .menu__icon::before,
    .menu__icon::after{
        background: var(--pseudo-backgroundcolor);

    }

And this is the JavaScript code:

const iconMenu = document.querySelector('.menu__icon');
const root = document.querySelector(":root");
let styleRoot = window.getComputedStyle(root)
let valueProp = styleRoot.getPropertyValue("--pseudo-backgroundcolor")
if (iconMenu) {
    const menuBody = document.querySelector('.menu__body');
    iconMenu.addEventListener("click", function (e) {
        document.body.classList.toggle('_lock');
        iconMenu.classList.toggle('_active');
        menuBody.classList.toggle('_active');
        
        switch (valueProp) {
            case 'yellow':
                root.style.setProperty("--pseudo-backgroundcolor", 'white');
                break

            case 'white':
                root.style.setProperty("--pseudo-backgroundcolor", 'yellow');
        }
    })
}

Alternatively, you can use if/else statements:

if (valueProp == 'white') {
    root.style.setProperty("--pseudo-backgroundcolor", 'yellow');
}
if (valueProp == 'yellow') {
    root.style.setProperty("--pseudo-backgroundcolor", 'white');
}

I'm having trouble understanding why the switch and if/else constructions are not working. The function doesn't seem to recognize it.

Answer №1

Ensure to remove any whitespace in the valueProp. Consider using .trim() on this variable before performing comparisons.

let valueProp = styleRoot.getPropertyValue("--pseudo-backgroundcolor").trim()

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

Encountering an unusual reactivity problem involving Firebase (Firestore) when using Vue.js and Vuefire

I'm facing a strange issue and I'm completely stuck. Here is the component in question: <template> <v-card elevation="0"> <h2>Accounts</h2> <v-simple-table fixed-header height="300px"> <template v ...

I encountered a "TypeError: Unable to access property 'name' of undefined" error when attempting to export a redux reducer

UPDATE: I encountered an issue where the namePlaceholder constant was returning undefined even though I was dispatching actions correctly. When attempting to export my selector function, I received an error: Here is the component code: import React, { ...

What could be the reason behind the malfunction of this jQuery post request?

I am currently studying AJAX with jQuery, but I am facing an issue with my registration system. The following code does not seem to work: $('#submitr').click(function () { var username = $('#usernamefieldr').val(); var password ...

Align images of varying sizes vertically within div containers, even when the image is larger than the div itself

I'm facing a challenge when it comes to aligning images vertically inside divs. The problem arises due to the following conditions: The images will have varying and unknown sizes. These images are larger than the divs they are contained in, requiri ...

How can I position two divs side by side within an Appbar?

I would like the entire Container to be in a single row, with the Typography centered as it already is, and the toggle-container to float to the right <AppBar className={styles.AppBar}> <Toolbar> <Container> ...

Calculating and modifying a specific value in my local storage using JavaScript

I've been working on a code that allows me to add, display, and delete objects in local storage. It's functioning fine, but I'm facing an issue when trying to update a specific object. Instead of modifying just the particular object I want, ...

Troubleshooting IE compatibility issues with jQuery .hide() method

I am encountering a curious issue with hiding span elements using CSS (display: none;). Upon page load, I expect the first span element to be displayed, which it does in all browsers except IE7. This anomaly has left me perplexed as there is no unusual cod ...

Does using the HTML doctype result in adding extra whitespace?

Could someone provide an explanation as to why setting a doctype of <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> and <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"> results in different rendering of the following ...

Having trouble locating and interacting with the textarea element in Salesforce using Selenium Webdriver

Encountering an issue with the Selenium Webdriver where it throws an error stating that the element is not visible and cannot be interacted with when attempting to access a textarea. 1. The textarea is located within a pop-up window, which can be accessed ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

Dynamically inserting a new row into a table with the power of jQuery

Currently working on dynamically adding rows to a table through jQuery in my project that follows MVC design pattern. I have set up a loop for the added rows, but need help with the script. Here is my code snippet for the loop : <?php $viewTableR ...

What causes pagination to be displayed outside of the main section in Firefox when using swiper?

When using swiper, why does pagination display outside of the main section in Firefox when inserting slides with different content lengths? This issue seems to only occur in Firefox and not in other browsers like Chrome. I have noticed that using two boots ...

Adding a border-top overlay to vertical navigation

I'm working on a vertical navigation bar and I'd like to make some styling changes. Here's the current setup (View jFiddle): <style> ul{ list-style-type: none; } li{ display: block; margin: 0; padding: 10; border-top: 1px d ...

using jQuery to eliminate an HTML element based on its attribute

How can I remove an element with the attribute cursor = "pointer"? I want to achieve this using JavaScript in HTML. Specifically, I am looking to remove the following item: <g cursor="pointer"></g>. It's unclear to me why this element has ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...

Express router route encountered a 404 Error

The first API endpoint is functioning correctly, however when attempting to access the second route, I am encountering a 404 error. Upon sending a GET request to http://localhost:3000/api/posts/, the response received is as follows: { message: "TOD ...

Difficulty encountered while implementing Ajax POST in CodeIgniter

I've been working on a project similar to a ticket system that occasionally requires lengthy answers. When using CKEDITOR in the answer area, the agent's changes are automatically saved to the database using Json GET. However, I encountered an er ...

In what ways can we utilize a consistent state across various tabs or pages?

One feature of my application is a dynamic chart with various settings such as filters and time ranges. I want to save these settings in the app's state so they can be shared with other components on different pages. However, when switching tabs and r ...

Updating the Highcharts chart when new data is available

Utilizing Highcharts, I am looking to have this chart update every second. Here's my current setup: JSFiddle I've implemented a timer with window.setInterval(updateChart, 1000); which successfully updates data each second. However, I'm uns ...

The updated version of Angular from 13 to 16 has implemented a new default value for primary colors

I recently upgraded my angular (+material-ui) system from version 13 to 16, and encountered an issue with the primary color of my custom theme. It seems that the value is no longer being recognized and defaults to blue. After updating the angular version, ...