Changing the color of a div element dynamically with JavaScript

Is there a way to improve the code below so that the background color of this div box changes instantly when clicked, without needing to click twice?

function updateBackgroundColor(platz_id)
{
    if(document.getElementById(platz_id).style.backgroundColor == "rgb(0, 168, 0)")
    {
        document.getElementById(platz_id).style.backgroundColor = "blue";
        return;
    }
    document.getElementById(platz_id).style.backgroundColor = "rgb(0, 168, 0)";
}
<div class='div_platz' onclick='updateBackgroundColor(this.id)' id='".$row['platz_id']."'>".$counter."</div>

Answer №1

To easily change the color using CSS, you can toggle a class with a blue background-color by using .classList.togle('class-name')

function choose_seat(seat_id) {
  document.getElementById(seat_id).classList.toggle('bg-blue');
}
div {
  background-color: rgb(0, 168, 0);
}

.bg-blue {
  background-color: blue;
}
<div class='seat_div' onclick='choose_seat(this.id)' id='".$row[' seat_id ']."'>".$counter."</div>

Answer №2

element.style specifically points to inline styling (defined using the HTML attribute

style="background-color: blue;"
). At the beginning, your element does not contain such an attribute.

Instead of inline styles, consider utilizing a selected CSS class and toggling it upon click:

.div_platz { background-color: rgb(0, 168, 0); }
.div_platz.selected { background-color: blue; }
<div class='div_platz' onclick='this.classList.toggle("selected")' id='".$row['platz_id']."'>".$counter."</div>

For better practice, avoid using inline event listeners. Instead, add the listener with JavaScript:

document.addEventListener('DOMContentLoaded', () => {
  let places = document.querySelectorAll('div.div_platz');
  for (const place of places) {
    place.addEventListener('click', function() {
      place.classList.toggle('selected');
    })
  }
});
.div_platz { background-color: rgb(0, 168, 0); }
.div_platz.selected { background-color: blue; }
<div class='div_platz' id='".$row['platz_id']."'>".$counter."</div>

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 wider background color for active nav bar links in CSS - A step-by-step guide

I've been working on customizing a CSS navbar and I've managed to get it to work as desired. However, I'm facing an issue with the active state background color, which seems to be the same width as the text itself. I've spent hours sear ...

To enable communication between methods, you can easily add a property to a JavaScript class component

Is there a better way to communicate between methods in a class? class T extends React.Component { constructor(props) { super(props) this.a = false; } methodA { //will set 'a' in this method, maybe async. } ...

What is the best way to accomplish this task with promises (using the Q library)?

I am currently working on an app using express.js and mongodb. My goal is to fetch all posts if the database is available, otherwise an error will be thrown. I am utilizing the Q package for promises, but I am struggling to implement the desired functional ...

How can I convert an Array into a Dictionary using JavaScript?

Is there a clever method (perhaps using a map function) to restructure my data object from this: [ {id: 1, from: "1/1/2021", to: "1/2/2022"}, {id: 2, from: "1/3/2021", to: "1/4/2022"}, {id: 1, from: "1/5/2 ...

Transformation of a JsonString into an array with the help of Angular.js

I have a JsonString that contains information about different car models. [{ "mileage": 12033, "name": "Ford", "model": "Focus", "engine": "3 gophers on a treadmill", "color": "green" }, { "mileage": 85000, "name": "Chevy", ...

Tips for integrating CSS keyframes in MUI v5 (using emotion)

Hey there! I'm currently working on adding some spinning text, similar to a carousel, using keyframes in my React app. The setup involves MUI v5 with @emotion. Basically, I want a "box" element to show different words every few seconds with a rotating ...

Symfony allows for the addition of an embedded collection prototype with an empty string

It seems like I must be overlooking something simple. I'm currently referencing this guide http://symfony.com/doc/current/cookbook/form/form_collections.html and aiming to include a link/button for adding more filters to a brand. However, the data-pr ...

Execute a Bash script using Node.js based on a request from the client

I'm trying to find a way to execute a server-side script when a user clicks a button in the browser... After doing some research, I still can't seem to figure it out. Here's what we have: A Node.js server running on Fedora Red Hat (on lo ...

AngularJS single page applications experiencing issues with loading scripts and stylesheets upon page reload

Homepage Setup : <ng-view></ng-view> Angular Routing Configuration : when('/', { url: '/', templateUrl: 'site/home', controller: 'indexController' }). when(&apos ...

Extracting JSON data within ajax's success callback

I am currently working on parsing and displaying JSON data that is returned from a server. To accomplish this, I have set up an AJAX call that reads user input, sends it to a PHP page via POST method, and the PHP page var_dumps the array containing the JSO ...

Cannot use Object.keys function in AngularJS

For my UI.Bootstrap accordion, I have set up the heading as follows: <accordion-group ng=repeat="(cname, stations) in byClient"> <accordion-heading> {{ cname }} <span class="pull-right"> {{ Object.keys(stations).length }} Sta ...

What steps should I take to repair this array table?

I've created a simple array table that uses 3 user-defined values to determine the value of a variable. Although I've written similar code in the past, I'm having trouble figuring out why this one isn't working. The table is quite large ...

Obtaining the ID from a JSON object in react.js ES6: A Comprehensive Guide

I have an array of JSON objects containing properties like Name, ID, and Address. My goal is to retrieve the IDs from all objects in this JSON array using react.js ES6. If anyone could offer guidance on how to accomplish this task, it would be greatly appr ...

Tips for transferring information between routes in Node.js using Express.js

How can I add a specific attribute to the request object and access it from another route after redirection? Below is an example of what I am looking for: const express = require('express') const app = express() app.get('/test1',(req, ...

Want to learn how to create an image magnifier using just one image?

At first, I created an image magnifier that would zoom in when the user hovered over the image. However, now I am looking to switch to a lens zooming method that uses only one image. ...

Is there a way to set a personalized callback function when closing a modal with MicroModal?

I've been utilizing MicroModal for showcasing a modal window. Everything seems to be working smoothly, except for when I try to trigger an event upon closing the modal. It's unclear to me where exactly I should implement this callback function. ...

The placeholder within my input moves up and down when switching the input type from password to text

Currently, I am encountering an issue with the styling of a standard input element in React. Specifically, the placeholder text moves up and down by about 2px when viewed on Chrome, while there are no problems on Safari. How can I go about resolving this i ...

Retrieve the parent object within a constructor function

Is there a way to access the parent object when calling a function contained inside that object as a constructor without explicitly referring to it? Take a look at this scenario: var customers = { // Number of customers count: 0, // Naturally ...

A complete guide on utilizing *ngFor in Angular to display data rows

I am facing an issue with using *ngFor to create new "rows" for adding new categories dynamically. Although there are no errors displayed when I run the program, the intended functionality is not achieved. I have tried making some modifications but it see ...

PHP is adding unique characters like   into the database records

Description : Having an issue with adding a text to a content editable div. When clicking the button, I am trying to extract all the text from the div and send it to php successfully. However, when saving it to my database table, the text gets corrupted. A ...