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

Using React Material UI icon within an auto complete feature

https://i.stack.imgur.com/W3CmF.png I am struggling to incorporate the target icon into the autoComplete component. After reviewing the documentation, I have been unable to find a solution. In TextInput, a similar outcome can be achieved by implementing ...

The outcome of the Python web crawling did not meet our expectations

After using Selenium to scrape web data, I encountered an issue where it only displayed 96 out of 346 products instead of the expected 346. Does anyone have suggestions on how to fix this problem? The crawling code is placed right after the loop for clicki ...

What is the best way to manage undefined status in react after the user chooses to cancel selecting a file?

Having an issue with my simple Input file type in React. I'm storing the selected file in state, but when I click the clear button, the state doesn't actually get cleared. This leads to {selectedFile.name} throwing an undefined error if the user ...

Choosing specific elements with Selenium using OR/AND operations in Python

I am encountering an issue while working with Selenium using Python. Here is a preliminary example of my code snippet. <body> <button info="content1" aria-label="1">"Click 1"</button> <button info ...

What could be causing the partial to not load JavaScript properly?

Hello, I am a newcomer to Angular and I'm currently working on implementing the slick carousel. It functions properly on the index page, but when I try to use the same HTML in a partial and include it with ng-view, it doesn't work as expected. T ...

Tips for streamlining the JSON parse object prototype in JavaScript

I recently had a JavaScript object that was created without a prototype. let bar = Object.create(null); After reading and parsing a JSON file in Node.js, I reassigned the parsed data to bar. Here's how: fs.readFile('data.json', 'utf8 ...

Having trouble installing npm package in Angular project

After cloning my project from GitLab, I encountered an issue while trying to install the NPM packages. When I ran npm install, an error popped up: https://i.stack.imgur.com/WNT5s.png Upon checking the log file, I found the following error message: 3060 ...

Utilize Jasmine's AJAX spy to intercept and inspect the error request

I am encountering an issue while trying to monitor the ajax error request and receiving the following error message. Can someone assist me with this? TypeError: e.error is not a function Code snippet for JS testing : function postSettings() { $ ...

What is the method for determining the level based on the provided experience points?

I've created a formula that can calculate experience based on specific levels and another formula that calculates the level based on given experience. However, there seems to be an issue with the second function as it is not returning the expected val ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

Implementing Click-Activated Scroll-to-Div Feature in React

I need to implement a scroll-to-div feature in my React App. However, the current structure of my app is preventing me from passing refs as props correctly, making it challenging to utilize ref.current.scrollIntoView(). The layout of my code looks like th ...

What is the best way to showcase a unique quote right when the webpage is opened?

I'm currently developing a random quote application. I want the quote to be displayed when the page loads instead of waiting for the user to click a button. I've tried invoking a function, but it's not working as expected. Any advice would b ...

Is it possible to transfer a Mongo connection to JQuery code using socket.io?

I'm currently working on setting up a global MongoDB connection in my node.js web app. Here is what I have so far: var MongoClient = require('mongodb').MongoClient; var mconn = null; MongoClient.connect('mongodb://myHost:27017/users&a ...

Unable to access static library Java Script file path using NSBundle

I have integrated a static compiled library into my project, which includes a JavaScript resource. At a specific event in my app, I need to execute the JavaScript file from this library. However, I am facing an issue where the path to the JS file appears ...

Safari is having trouble correctly displaying a CSS3 gradient with transparency

Here's a tricky puzzle for you. The gradient below is not displaying correctly in Safari, but it works perfectly fine in Firefox and Chrome: background: linear-gradient(transparent 124px, #de6230); I've even attempted the following fix without ...

Issue with integrating Google Spreadsheet as the data source for a Next.JS website: updates are not reflecting on the website pages

The website for this restaurant was created by me, using Google Spreadsheet to populate the menu pages. I chose this method for its simplicity and familiarity to the client. I'm utilizing the google-spreadsheet package to extract necessary informatio ...

What is the best way to activate a component within Angular 2 that triggers the display of another component through method invocation?

I have created a popup component that can be shown and hidden by calling specific methods that manipulate the back and front variables associated with the class. hide() { this.back = this.back.replace(/[ ]?shown/, ""); this.front = this.front.replace( ...

Implementing the session injection into a request body within an asynchronous function in Node.js

I've been trying to inject a session value into the request in order to use it in various parts of my app. What I'm currently attempting is to call a function by providing an ID to search for a user in the database and retrieve the name of that s ...

Executing a server-side Java function from client-side JavaScript or jQuery on a JSP page

My JSP file has a dropdown list where I can select different entity kinds. Upon selecting an entity kind, I want to populate another dropdown list with the field names associated with that entity kind. This requires calling a JavaScript function when chang ...

Tips for making a range slider in react-native

Check out my range slider I'm having trouble with changing values by clicking on them. Is there a way to enable sliding the range slider instead? Thanks for any help. ...