What is the best way to change CSS style for a button when clicked using JavaScript?

Is there a way to switch the background style of a CSS div when clicking the same button?

function changeBg() {
  var divElem = document.getElementById("change-bg");
  if (divElem.style.backgroundColor === "yellow") {
    divElem.style.backgroundColor = "red";
  } else {
    divElem.style.backgroundColor = "yellow";
  }
}
body {
  margin: 0;
}

#change-bg {
  /* Extra Text Formatting */
  padding: 10px;
  text-align: center;
  /* Primary Background Color */
  background-color: yellow;
}
<div id="change-bg">
  <h3>
    Hello World
    <br/>
    <button onclick="changeBg();">Change Color</button>
  </h3>
</div>

Currently, it changes color to red. How can I make it revert back to its original color (yellow) when clicking the same button?

Feel free to explore the JSFiddle. I believe an If-Else statement could solve this issue. However, I am having trouble implementing it.

Answer №1

To switch the class name string and revert it back when the classList already contains it, you can utilize classList.toggle with the code snippet below:

const box = document.querySelector(".bg")
const btn = document.querySelector(".btn")

btn.addEventListener("click", () => {
  box.classList.toggle("blue")
})
.bg{
  background: red;
  width: 100px;
   height: 100px;
}

.blue{
  background: blue
}
<div class="bg"></div>
<button class="btn">Toggle it</button>

Answer №2

Try out this method exactly as presented!

function modifyBackground() {
  var targetElement = document.getElementById("modify-background");
  targetElement.classList.toggle("change-color");
}
body {
  margin: 0;
}

#modify-background {
  /* Additional Text Styling */
  padding: 10px;
  text-align: center;
  /* Default Background Color */
  background-color: yellow;
}
.change-color{
  background-color: red !important;
}
<!DOCTYPE html>

<head>
</head>

<body>
  <div id="modify-background">
    <h3>
      Hello World
      <br/>
      <button onclick="modifyBackground();">Change Color</button>
    </h3>
  </div>
</body>

</html>

Answer №3

Here is an innovative approach using a toggle variable and the if-else method as suggested in the original post.

const backgroundDiv = document.getElementById("change-bg");
let toggleState = true;

function changeBackgroundColor() {
  backgroundDiv.style.backgroundColor = toggleState ? 'red' : 'yellow';
  toggleState = !toggleState;
}
body {
  margin: 0;
}

#change-bg {
  padding: 10px;
  text-align: center;
  background-color: yellow;
}
<div id="change-bg">
  <h3>
    Hello World
    <br/>
    <button onclick="changeBackgroundColor();">Change Color</button>
  </h3>
</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

PHP variable inaccessible

When using JQuery Ajax to call sessions variables from a PHP steamauth file, I encountered an issue. Even though the code works fine when "$data['test'] = "ok";" is used instead of "$data['test'] = $_SESSION['steamid'];", ther ...

Angular 2's Multi-select dropdown feature allows users to select multiple options

Recently, I encountered an issue with customizing CSS for angular2-multiselect-dropdown. I found the solution in this link: https://www.npmjs.com/package/angular2-multiselect-dropdown. I have included my code below. Any assistance in resolving this matter ...

No matter how tall I make it, the scroll bar just won't stop showing

Check out this fiddle for more information: http://jsfiddle.net/LAueQ/ Even after increasing the height of the campaignDiv div, the scrollbar keeps showing up. If possible, I would like to avoid using overflow: hidden. ...

What is the process for updating a particular div element?

I am currently developing a webpage that allows users to select an item, and the relevant information will be displayed. On this page, I have incorporated two buttons: btnBuy0 and btnBuy1. The functionality I am aiming for is that when BtnBuy0 is clicked ...

Tips for shifting a designated row upward in Chrome using JavaScript

Currently, I am working on a Javascript function that moves up a selected row. However, the issue I am facing is that when the row moves up, the old row is not being removed. For instance, if I move up the 'bbbb' row, it successfully moves up bu ...

Display/hide a div containing distinct content

Upon clicking an image in the carousel, a position: absolute; div should appear containing two different images and a form related to the initial picture clicked with a submit button. How can I implement a show/hide feature that displays unique content for ...

jQuery live DataAttribute manipulation

Here is the code snippet I am working with: <head runat="server"> <title>Sidebar</title> <link href="css/style.css" rel="stylesheet" /> <script src="scripts/jquery-1.11.1.min.js"></script> <script src ...

Unable to trigger the show_popup function by clicking the button

Why won't this piece of code function as expected? <script src="web_push.js"></script> <body> <button onclick="show_popup()"> Button </button> </body> The content of web_push.js file is shown below ...

Is there a way to determine if a table cell contains overflowing text compared to another cell?

Is there a way to detect if the content of the fourth td overflows from the second td? I am looking for a method to determine which td has overflowed text and identify which td's text is overflowing. What approach can be used to determine which td i ...

What is the best way to eliminate the space following the image?

Something strange happened, and now there's a big gap following the top image. I was working on making the code responsive and then inserted this image, which messed everything up. Any ideas on what I might be doing wrong? I want the image to be close ...

The upload directory fails to include the folder name when sending a file

After experimenting with the new directory upload feature, I encountered an issue where the server request did not preserve the exact folder structure as expected. Here is the HTML code snippet: <form action="http://localhost:3000/" method="post" enct ...

Reveal the table only once a search has been completed

Currently, I am in the process of developing a small project and my aim is to have the table with the results appear only upon clicking the button or initiating a search. If you are interested, you can view it at this link: . My objective is to keep the t ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

At times, the CSS fails to load at first and does not refresh correctly when using F5 or CTRL F5, yet it occasionally loads when clicking on links

After dedicating a full day to trying to solve this issue, I am reaching out for some assistance. As a newcomer here, I apologize if this question has been asked before (I did search extensively and found nothing). The website I'm constructing for my ...

Saving data in multiple collections using MongoDB and Node.js: A comprehensive guide

In a recent project of mine, I have implemented a combination of nodeJS and mongodb. My main goal is to store data in multiple collections using just one save button. Below is the code snippet that I am currently working with: var lastInsertId; loginDat ...

Stuck on loading screen with Angular 2 Testing App

Currently working on creating a test app for Angular 2, but encountering an issue where my application is continuously stuck on the "Loading..." screen. Below are the various files involved: app.component.ts: import {Component} from '@angular/core& ...

Tips for updating the display by fetching data from a database through a websocket

I am looking for a solution to update a specific part of my webpage without having to refresh the entire content. On my index.html page, I have three panels displaying various ticket statuses. I want to automatically update the number of resolved tickets s ...

How can we translate this php json_encode function into Node.js?

Seeking the equivalent Node.js code for this PHP Script: $SMA_APICall = "https://www.alphavantage.co/query?function=SMA&symbol=".$symbolValue."&interval=15min&time_period=10&series_type=close&apikey=R3MGTYHWHQ2LXMRS"; $SMAres ...

Filter jQuery search results for classes with identical names

I am new to using jQuery, so please excuse my lack of experience. My current challenge involves 'getting a reference to an object wrapped in a class', but there are multiple classes with the same name. How can I specifically target and retrieve t ...

JavaScript: Reorder an array to alternate between largest and smallest elements, starting with the largest

When working with an array of integers that need to be sorted in a specific order, such as: [1, -1, -3, 9, -2, -5, 4, 8,] We must rearrange them so that the largest number is followed by the smallest number, then the second largest number followed by the ...