Updating the color of HTML button text dynamically using JavaScript function

I am attempting to create a function that will change the text color of a button in a sequence - red on the first click, green on the second click, and back to black on the third click (and so forth). I thought this would be straightforward to achieve with an if else statement that checks the current color of the button. I have managed to successfully change the color on the initial click, but subsequent clicks do not produce any results. Each button has an onclick attribute calling the function as follows:

function changeColor(alphaButton) {
  if (alphaButton.style.color == "black") {
    alphaButton.style.color = "red";
  } else if (alphaButton.style.color == "red") {
    alphaButton.style.color = "green";
  } else if (alphaButton.style.color == "green") {
    alphaButton.style.color = "black";
  }
}

The if statement is functioning correctly, but it seems to stop working after the initial step. I would appreciate any assistance in resolving this issue.

[UPDATE]

After further investigation, I discovered the problem with my code. It turns out that I had not properly defined the text color (despite believing I had done so inline). After correcting this, the functionality now works perfectly. However, I was surprised to learn that specifying black text explicitly was necessary for it to appear as such. This experience has been frustrating but educational.

Answer №1

It is generally advised not to depend on reading back style properties as the button's initial style.color may be empty unless manually set. There is a possibility that the color could have been specified as #000, which produces the same effect but can potentially disrupt your code.

My approach would be as follows:

const colors = ["black", "red", "orange", "green", "blue"];

function changeColor(button) {
  var current = Number(button.dataset.ci || 0); // initialized to 0 on first click
  current = (current + 1) % colors.length; // clamping array index
  button.dataset.ci = current; // storing new value in element
  button.style.color = colors[current]; // setting color
}
<button onclick="changeColor(this)">Click</button>

Answer №2

When dealing with if and else conditions, it's important to remember to use the === operator for comparing color style and the color string. You should avoid using the = operator, as it is meant for assignment.

Answer №3

In your conditional statement, you are setting variables based on the current color of the alpha button. Here's a revised version:

function toggleColor(alphaBtn) {
    if (alphaBtn.style.color === "black") {
        alphaBtn.style.color = "red"; 
    } else if (alphaBtn.style.color === "red") {
        alphaBtn.style.color = "green"; 
    } else if (alphaBtn.style.color === "green") {
        alphaBtn.style.color = "black"; 
    }
}

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

Prevent divs from jumping to a new line with the float property

I've been busy working on a responsive webpage and so far, everything is going smoothly. The only issue I'm facing is that when the browser window size decreases and reaches a certain point, the div elements jump to the next line. Take a look at ...

The error message I'm receiving is saying that the map function is not recognized for the posts variable (posts.map

I encountered a puzzling error, even though everything seems fine: posts.map is not a function import React from 'react' import { useSelector } from 'react-redux' export const PostsList = () => { const posts = useSelector(state = ...

The integration of express and cors() is malfunctioning

Currently, I am developing a React application and facing an issue while trying to make an API call to https://itunes.apple.com/search?term=jack+johnson In my project, there is a helper file named requestHelper.js with the following content : import &apo ...

What is the most effective method for data binding using [innerHTML] in Angular 4?

One issue I've encountered is that in Angular 4, there are limited ways to perform data binding between HTML and TypeScript, such as {{myText}}, [], (), and [innerHTML]="myText". Which method is the most effective for binding a simple variable to HTM ...

Encountering 404 Error in controller's action methods following deployment on remote server

.JS Script $("#drpdwn").change(function () { var filter1 = document.getElementById("drpdwn").value; window.location = '/Controller/GetByFilter?filter=' + filter1; }); Action Method in Controller: public ActionResult GetByFilter(string ...

Tips for limiting users to inputting only alphanumeric characters and excluding special characters in an input field using Angular 8

How can I prevent users from inputting special characters in an input field and only allow alphanumeric values? The code that I have implemented so far does not seem to be working as intended. When a user enters a special character, it still shows up in th ...

Tips on saving an array as a variable

Can anyone help me figure out how to store a PHP variable into a JavaScript variable? var myArray; function retrieveData(id) { $.post( "main/updater.php", { id:id } ).done(function( data ) { myArray = data; }); } I&ap ...

The JavaScript audio is not working for the first three clicks, but starts playing smoothly from the fourth click onwards. What could be causing this issue?

$(".btn").click(function(event){ playSound(event.target.id); }); function playSound(name){ $("." + name).click(function() { new Audio("sounds/" + name + ".mp3").play(); ...

Tips for utilizing CSS perspective to align a div so it seamlessly fits within an SVG laptop display

Confusion may arise from the question at hand. My goal is to utilize CSS to absolutely position a div with perspective in a way that resembles it being inside the laptop screen I created with an SVG. I am under the impression that achieving this effect is ...

Ways to stop the click event from being triggered in JQuery

There is a single toggle switch that, when clicked, switches ON and a popup with close and OK buttons appears. However, if the toggle is clicked again, it switches OFF and disappears. The specific requirement is that with every click where the toggle switc ...

What are the steps to set up auto-building with create-react-app?

I've been utilizing create-react-app for some time now. Autoreloading with 'npm start' or 'yarn start' has been working well on its own, but now I'm facing another issue. Currently, I am running the app on an Express server th ...

Enhance your CouchDB experience by customizing templates to include unique headers and footers

I am currently using CouchDB and CouchApp to host a web application. I have experience with Django and Jinja2, where I can extend templates in two different ways: {% include "header.html" %} or {% extends "base.html" %} <<<---- my preferred me ...

Check the Full Calendar to see if any events are scheduled for today

I have a group of users who need to save their availability. Currently, I am utilizing Full Calendar and looking for a way to prevent them from adding the same event multiple times on a single day. My tech stack includes VueJs and all events are stored in ...

Achieving a full-height accordion with each pane taking up the entirety of the viewport using Bootstrap 4

https://i.sstatic.net/LqhXn.png I found this image which perfectly explains what I'm trying to achieve. This is my current code: <div class="accordion" id="myAccordion"> <div class="card"> ...

Get the image file using JavaScript

I'm wondering how to successfully download an image using javascript. Every time I try, it shows a failed error message. <div> <button onClick=this.downloadImage(event, "http://example.net/media/image.png")>Download</button> </di ...

Enhance the CSS styling for the React-Calendly integration in a React project

I am trying to customize the CSS of an Inline Widget called React Calendly. I have attempted to use React Styled Component Wrapper, Frame React Component, and DOM javascript but unfortunately, the design changes are not reflecting as desired. Specifically, ...

Material UI is failing to apply its styles

I tried customizing the default theme provided by Material UI, but unfortunately, the styles are not applying. Can anyone help me with this issue? In My Header.js file, I faced an issue where the customized style was not being applied as expected. const u ...

Updating language settings on-the-fly in a Vue application does not automatically refresh the translated content displayed on the website

My Vue app is quite large, built with Vuetify, and I recently integrated vue-i18n into it. The json translation files are set up correctly, and the $t() calls work fine in my components and other .js files. However, I'm struggling to change the locale ...

Customize Zurb Foundation: Applying styles to specific child elements based on current screen size (large, medium, small)

For wide displays, I aim to give a distinct border to each 7th element. However, on smaller screens, I wish to apply these styles to every 4th element instead. Is there a way for me to nest my styles within .small, .medium, and .large classes? ...

Leveraging TypeScript's "this" keyword within an interface

I am currently working on a personalized interface where I aim to determine the type of an interface value within its implementation rather than in the interface definition, without using generics. It is important to note that these implementations will al ...