What is the best way to utilize an event listener in JavaScript to dynamically update the background color of my CSS?

I am trying to modify the background color of a list item, but I am encountering an issue with an if-statement. When I remove the if-statement and directly set the background color, it works fine. However, when the if-statement is included, it fails to work as expected. I need some assistance in understanding why this is happening.

HTML

<ul id="testList"> Test List
    <li id="item1">Item 1</li>
    <li id="item2">Item 2</li>
</ul>


CSS

#testList {
    width: 100px;
    background-color: grey;
    margin: 200px 0px 0px 50px;
    list-style-type: none;
}
#testList li {
    color: black;
    padding: 10px;
    border: 1px solid black;
}
#testList li:hover{cursor: pointer;}
#item1 {background-color: white;}


Javascript

var item1 = document.getElementById('item1');
function setColor(){
    if (item1.style.backgroundColor == 'white'){
        item1.style.backgroundColor = 'green';
    } else if (item1.style.backgroundColor == 'green'){
        item1.style.backgroundColor = 'white';
    }
}
item1.addEventListener('click', function(){setColor()}, false);

Answer №1

It seems like the issue lies in the initial background color value not being set for the item. While item 1 has a white background color applied through CSS styling, accessing it directly via item1.style.backgroundColor will only return inline values.

var item1 = document.getElementById('item1');
function setColor(){
    if (!item1.style.backgroundColor || item1.style.backgroundColor == 'white'){
        item1.style.backgroundColor = 'green';
    } else if (item1.style.backgroundColor == 'green'){
        item1.style.backgroundColor = 'white';
    }
}
item1.addEventListener('click', function(){setColor()}, false);
#testList {
    width: 100px;
    background-color: grey;
    margin: 200px 0px 0px 50px;
    list-style-type: none;
}
#testList li {
    color: black;
    padding: 10px;
    border: 1px solid black;
}
#testList li:hover{cursor: pointer;}
#item1 {background-color: white;}
   <ul id="testList"> Test List
    <li id="item1">Item 1</li>
    <li id="item2">Item 2</li>
</ul>

Answer №2

To properly execute a swap like this:

Start by defining a class

.background-green {
    background-color: green !important;
}

Then, you need to check if a specific element has this class. If it does, remove it. If not, add it.

function toggleBackgroundColor() {
    let element = document.getElementById("myElementId");
    if (element.classList.contains("background-green")) {
        element.classList.remove("background-green");
    }
    else {
        element.classList.add("background-green");
    }
}

By following these steps, the element will switch between its default color and green. You can set the default background color to white in your CSS.

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

When submitting the form for the zip code input, use an XMLHttpRequest to input the zip code and retrieve the corresponding city

I'm currently working on a project that involves inputting zip codes and retrieving the corresponding city information from . In the future, I plan to parse this data and store it as variables in my program while potentially using longitude/latitude f ...

Mobile devices do not support CSS3 transition functionality

I have a straightforward div setup that smoothly transitions upward when swiped up on the screen, functioning perfectly on my desktop. However, I am encountering difficulties getting the transition to work on my mobile device (also tested on an Android emu ...

What causes the discrepancy between the values of 'form.$invalid' and the '$invalid' property of 'form'?

When trying to disable a button based on the status of a form, I encountered an interesting issue. After setting all the form values to null, I noticed that when I use the code: console.log('$scope.assignNewForm.$invalid: ' + $scope.assignNewForm ...

Is it possible to fire a Socket.io emit with a scroll event?

Can you trigger an emit on a gesture or scroll event, similar to how it works on a click event? I'm trying to create something like this: https://www.youtube.com/watch?time_continue=38&v=tPxjxS198vE Instead of relying on a click, I would like to ...

Styling text over an image when hovering with CSS and HTML

I have successfully implemented a functionality, but I am looking to enhance the appearance of the text displayed when an image is hovered over. Below is the current code snippet: .ecommerce-categories [class^=col-] > a:before { content: attr(data- ...

Error: Unable to access the 'create' property of an undefined object while utilizing sequelize to register a user and add an entry

Whenever I try to execute this controller, an issue arises indicating a problem with the recognition of the .create method from the model. What is the correct way to import Sequelize in order to utilize it effectively? const db = require("../Models/m_use ...

It appears that Promise.all is not adequately ensuring that all tasks are completed before moving on

In my current project, I am trying to achieve a complex cycle where an HTTP GET request is executed to fetch data, followed by the creation of multiple "subrequests" based on that data. The goal is to ensure that the next iteration of the cycle begins only ...

Enhancing Custom Elements in JointJS with a Port

I followed the steps from the jointjs tutorial to create a custom element, which looks like this: CustomRect = joint.dia.Element.define('example.CustomRect', { attrs: { rect: { refX: 0, refY: 0, refWidth: '116', ...

Issue with Javascript code - function does not provide a return value

I have a JavaScript function that checks for a value in a text box. If the text box is not blank, it outputs a statement. The text box takes a numeric value, and I want to include that numeric value in the outputted HTML. Here is the HTML code: <br> ...

Exploring Django's view field for efficient data rendering

Is it possible to display multiple views for a single page/template? For instance, imagine a website where users can submit movie reviews and read others' reviews as well. Now, I need to add an edit button to the review pages but only want the button ...

Problem: Toggle functionality not working properly in JavaScript

As a beginner, I am facing an issue with multiple toggle buttons. They work fine individually, but when nested within each other, only one toggle button works. After some research, I realized that I need to make adjustments to my JavaScript code. However, ...

Adjust the size of an input field in jquery or javascript based on user input

Ensure that an input text box can only contain a maximum of 13 numbers, but if the user enters a 14th number as a decimal point, then allow up to 16 numbers. HTML: <input type="text" maxlength="15" onkeyup="checkCurrency(this)"/> Script: func ...

Having difficulty populating the token in the h-captcha-response innerHTML and g-recaptcha-response innerHTML

I am attempting to use 2captcha along with Selenium and Python to bypass an Hcaptcha. After receiving my 2captcha token, I attempt to input it into the textareas labeled 'h-captcha-response' and 'g-captcha-response'. However, this app ...

What is the best way to retrieve the value of a textbox with a dynamic ID?

Within this section, you will find two input elements: one button and one textbox. The purpose of the qty-input is to input the quantity of products, and upon clicking the button via jQuery, the shopping cart is updated. While hardcoding as 1 works fine, I ...

How can Vue.js pass an array from a child component to its parent component?

I'm currently developing a contact book app and I have created a modal within a child component that contains a form with several input fields. My goal is to utilize the values entered in the form and add them to the parent component. I have successfu ...

Is there a way to send the HoDjango views.py context data variable to the ng-repeat filter?

I am attempting to implement a filter in Angular's ng-repeat where the value of selectedUserId is derived from a context_dict variable. The curly braces I am using for Angular are {--} This is my view.py file - extracting the user_id from the URL de ...

Tips for aligning 2 columns perfectly in a 3 column layout

I am facing an issue with a grid section where the grid-template-column is set for 3 columns, but sometimes the content loaded dynamically only fills 2 columns. I am attempting to center the columns when there are only 2. Despite going through the grid CS ...

FormControlLabel in Mat ui is not correctly utilizing the state

I've been using FormControlLabel for my custom checkboxes, but I'm encountering an issue where they don't reflect the state that is being passed to them. Despite the onchange handler updating everything in redux/BE correctly, upon initial re ...

Speeding up the loading time of my background images

body { background: url(http://leona-anderson.com/wp-content/uploads/2014/10/finalbackgroundMain.png) fixed; background-size:100% auto; } I have unique background images on each of my sites, but they are large in size and take some time to load due to bein ...

What is the best way to add borders to table cells that have a non-zero value

I am trying to create a table using a function and it currently looks like this: table { border: 1px solid; } td { width: 30px; height: 30px; text-align: center; } <table> <tr> <td>2</td> <td>0</td> ...