Would you like to learn how to dynamically alter a button's color upon clicking it and revert it back to its original color upon clicking it again?

My Upvote button starts off transparent, but when I click on it, the background color changes to green. What I need is for the button to become transparent again when clicked a second time. I've attempted using the following code snippet:

function changeColor(){
  var upVoteBtn = document.getElementById("upVote");
  if (upVoteBtn.style.backgroundColor === "transparent"){
    upVoteBtn.style.backgroundColor = "green";
    upVoteBtn.style.color = "black";
  } else {
    upVoteBtn.style.backgroundColor = "transparent";
  }
}
<button id="upVote" onclick=changeColor()>upVote</button>

Answer №1

Instead of directly applying styles in JavaScript, it's recommended to create a separate class with the necessary styles and then toggle this class using an event listener on button click, as @CBroe suggested.

document.getElementById("upVote").addEventListener("click", () => {
  event.target.classList.toggle("upvoted")
})
.upvoted{
  background-color:green;
}
<button id="upVote">upVote</button>

Answer №2

Give this a try!

var toggleBtn = true;
var thumbsUpBtn = document.getElementById("thumbsUp");

function vote(){
    if (toggleBtn){
        thumbsUpBtn.style.backgroundColor = "green";
        toggleBtn = false;
    } else{
        thumbsUpBtn.style.backgroundColor = null;
        toggleBtn = true;
    }
}
<button class="btn btn-outline-success" id="thumbsUp" onclick=vote()>Thumbs Up</button>

If you want to make it see-through, then simply use

thumbsUpBtn.style.backgroundColor = "transparent";
instead of null. Just like below.

var toggleBtn = true;
var thumbsUpBtn = document.getElementById("thumbsUp");
thumbsUpBtn.style.backgroundColor = "transparent";

function vote(){
    if (toggleBtn){
        thumbsUpBtn.style.backgroundColor = "green";
        toggleBtn = false;
    } else{
        thumbsUpBtn.style.backgroundColor = "transparent";
        toggleBtn = true;
    }
}
<button class="btn btn-outline-success" id="thumbsUp" onclick=vote()>Thumbs Up</button>

Appreciate your time and best wishes!

Answer №3

 function castVote(button){
        button.classList.toggle("active");
}
                      
.btn.active{
  background:green;
  color: #fff;
}
.btn{
  background: transparent;
  color: black;
}
<button class="btn btn-outline-success" id="upVote" onclick=castVote(this)>upVote</button>


Solution to the Problem

  • castVote(this) sends the element of the button
  • toggle() is used to add and remove the active class
  • .btn.active checks if the button has the active class or not

Answer №4

To optimize the code, it is recommended for the original poster to utilize the Element.classList and its toggle method. Additionally, they should consider transitioning away from inline event handling and instead embrace using the selector API in conjunction with EventTarget.addEventListener.

function toggleVotingState({ currentTarget }) {
  currentTarget.classList.toggle('voted');
}
document
  .querySelector('#upVote')
  .addEventListener('click', toggleVotingState);
.voted {
  color: black;
  background-color: green;
}
<button class="btn btn-outline-success" id="upVote">upVote</button>

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 dynamic animation effect on a div with a changing number of child elements

Currently, I am utilizing the nganimate library and have implemented an animation that affects the max-height property of a div. Here is a snippet of my code: CSS .sublist.ng-hide { max-height: 0; } .sublist { max-height: 1300px; overflow: hidden; ...

Retrieving Progress Updates from a PHP Script Using XMLHttpRequest

I am currently using JavaScript to execute an XMLHttpRequest to a PHP script that returns data. My goal is to display a progress bar for the user instead of a spinning circle, indicating the progress of fetching and receiving the data. While I understand t ...

`How can I trigger a JavaScript event when the content of an input field is modified?`

Currently, I am working on implementing validation in JavaScript. My goal is to provide the user with an alert whenever they modify the value of an input field. <input type="text" name="onchange" id="onchange" size="35" maxlength="50" /> ...

The last javascript file that was included has been overlooked

When using jqplot, I noticed that the last included plugin is being ignored. If I switch their positions, the first to last one works while the last one does not. There are no errors in the console to indicate what might be going wrong. Moving the canvasOv ...

Challenges with pjax/ajax and handling the browser's back button

I've implemented pjax to ajaxify my menu links, which works well until I encounter an issue with the browser back button. In my JavaScript file, I have both Common Script files (to load all necessary js files when the user hits the URL) and Script fil ...

What is the best way to customize multiselection in jqgrid?

jQuery("#grid").jqGrid({ datatype: "local", width:'auto', height: 'auto', multiselect:true, colNames:[ 'no' ], colModel:[ {name:'no', align:'r ...

What is the best way to show instructions immediately upon receipt of a response?

I'm currently working on developing a website similar to ChatGpt using the OpenAI API for GPT. However, there is a delay in generating responses with GPT taking a few seconds. As a result, my code only displays the instruction once the response from G ...

Identifying and handling errors in the outer observable of an RXJS sequence to manage

Encountered a puzzling rxjs issue that has me stumped. Here's the scenario: I have two requests to handle: const obs1$ = this.http.get('route-1') const obs2$ = this.http.get('route-2') If obs1$ throws an error, I want to catch it ...

Issue with JAWS screen reader failing to announce aria-expanded status

My aim is to ensure that the collapsed state is accessible in both NVDA and JAWS, but I am encountering issues with it displaying properly in JAWS. Does anyone have any suggestions on how to rectify this? I have included images of the code and link list b ...

Python selenium issue: Element not found in the document using locator (//input[@type='file']')

I'm attempting to automate the process of uploading a file using python. However, when I run the code below with python selenium, an error is thrown. I even added a 10-second wait to prevent synchronization issues. driver.execute_script('window ...

Creating a horizontal scrolling section for mobile devices using CSS

Looking to create a horizontal scroll area specifically for mobile devices, similar to the design seen here: https://i.sstatic.net/oSNqL.png Additionally, I want to hide the scrollbar altogether. However, when attempting to implement this, there seem to ...

Creating DOM elements upon successful completion of an AJAX request with jQuery has never been easier. Here's a

I'm currently working on a project where I am dynamically creating a list of checkboxes using jQuery's $.ajax method. function load() { $.ajax({ type: "POST", url: "*************", data: "************ ...

Warning: React detects a missing dependency within an interval in the effect

A webpage I developed using React and Next.js has the following structure. import Head from 'next/head'; import { useEffect, useState } from 'react'; import Header from '../components/Header'; export default function Home() { ...

Is there a way for me to convert my (TypeScript Definition) .d.ts file into a (JavaScript) .js file?

It seems that there are plenty of guides available on converting a file from .js to .d.ts, but not the other way around. Specifically, I have some code in .d.ts format and I would like to convert it into JavaScript. Can anyone offer assistance with this t ...

The text in the image caption has been drastically reduced along with the size of the image

Currently, I am dealing with the following code: <div style="min-width: 1000px;"> <p> Some text </p> <div class='div_img_left'> <img src="images/sth.png" alt="missing image" style="max-width ...

Manipulate a deeply nested JSON object in JavaScript by iterating through it and constructing a new data

Struggling to rearrange complex JSON data (data1) into a more organized format (data2). Progress has been slow. data1 is created by scanning a parent directory (recipes) for html files. data2 is the desired output structure using data1, where content wit ...

What is the best way to make an image clickable in Next.Js?

Is there a way to turn an image into a link in Next.Js? I have the Instagram logo that I want to use as a link to my Instagram page. I want it to open a new tab and redirect the user to my Instagram account when clicked. I would really appreciate any guid ...

Tips on getting the bot to react to a single "event" mentioned in the sentence, without multiple occurrences

Things are a bit complicated, but here's an example to illustrate: I've set up this event: client.on('message', async message => { if (message.content.toLowerCase().includes("megumin")) { message.channel.send("W ...

Fill the list items with values from the given array

I have an array called var array = ["one", "two"]; and I want to display each element in a separate list item. The desired output is: <li>Number one</li> <li>Number two</li> However, the current output is: <li>Number onetw ...

The command `grunt.option('force', true) isn't functioning properly

After reviewing the grunt.options documentation, my initial expectation was that I could initiate a Grunt task programmatically with the force option activated in this manner: var grunt = require('grunt'); grunt.option('force', true); ...