Modifying button appearance upon clicking using JavaScript

JavaScript:

const buttons = document.getElementsByClassName("togglebtn");
for (let i = 0; i < buttons.length; i++) {
   buttons[i].onclick = function () {
       this.classList.toggle("active");                               
   }
}

html:

<md-button class="md-fab togglebtn"></md-button>

css:

button.togglebtn:after {
   background-color: white;
   width: auto;
   font-weight: bold;
   margin-left: 5px;
   border: none;
   content:'';
}

button.togglebtn.active:after {
   width: auto;
   background-color: green;
   content:'close';
   font-size: 10px;
}

I am facing an issue where I can change the color of text but not the background color. My goal is to modify the color when a button is clicked. The :after in CSS works, but changing the color does not. Can someone please provide suggestions on what I may be doing wrong?

Answer №1

let buttons = document.getElementsByClassName("togglebtn");
let index;
for (index = 0; index < buttons.length; index++) {
  buttons[index].onclick = function() {
    this.classList.toggle("active");
  }
}
button.togglebtn.active {
  background-color: blue;
  color: #fff;
}
<button class="md-fab togglebtn">click me</button>

Answer №2

There seems to be a CSS issue at hand here. Instead of setting the style of after, you should set the style of the button and after separately:

var acc = document.getElementsByClassName("togglebtn"),
  i;
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
  }
}
button.togglebtn:after {
  content: '';
}

button.togglebtn.active:after {
  content: 'close';
}

button.togglebtn {
  background-color: white;
  width: auto;
  font-weight: bold;
  margin-left: 5px;
  border: none;
}

button.togglebtn.active {
  width: auto;
  background-color: green;
  content: ' close';
  font-size: 10px;
}
<button class="md-fab togglebtn">hello</button>

Answer №3

If you're working with AngularJS, it's recommended to utilize ng-class instead of relying solely on JavaScript:

var myApp = angular.module('myApp', []);
.active { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
    <button ng-class="{active: isActive}" ng-click="isActive =! isActive">Hello</button>
</div>

Answer №4

     .md-button.md-fab {
      line-height: 1% !important;
      min-width: 0;
      border-radius: 50%;
      position: fixed;
      margin-left: 400px;
      background-color: green;
      margin-top: -7px;
      }
      button.togglebtn:after {
        color: white;
        width: auto;
        margin-left: 5px;
        border: none;
        content:'open';
        font-size: 10px;

    }

button.togglebtn.active:after {
    width: auto;
    color: black;
    content:'close';
    font-size: 10px;
}

.md-button.md-fab {
    background-color: black !important;
}
.md-button.md-fab.active{
    background-color: yellow !important;
    content: 'yellow';
    color: white;
}

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 AJAX to load multiple pages asynchronously

Recently, I put together a website using the following script: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script> function loadpage(page) { document.getElementById( ...

How to extract information from a JavaScript object array in Node.js?

Currently, I am attempting to extract data from a JavaScript Object array by providing field names and then storing the data in an array. However, my current approach seems to be yielding incorrect results. Whenever I try to log the values stored in ' ...

Master the art of adjusting chart width on angular-chart with the help of chart.js

I am currently using angular-chart along with Angular and chart.js to create multiple charts on a single page. However, I am facing an issue where each chart is taking up the entire width of the screen. I have tried various methods to limit the width based ...

Manipulating Objects and Arrays

When I retrieve data from a database query in Node.js using Postgres with Knex, I get an array of objects structured like this: (condensed version) [ { tvshow: 'house', airdate: 2017-02-01T00:00:00.000Z }, { tvshow: ' ...

When using a function linked to an API request, an uncaught TypeError is thrown: Unable to access the 'includes' property of an undefined value

Utilizing the movie DB API (), I am displaying the results of my call on my page using Vue. The API supplies all the necessary data for me to achieve my objective, as demonstrated in this image https://i.stack.imgur.com/vP4I2.jpg Beneath each show's ...

Ways to eliminate the leading bullet point from an unordered list

I am currently working on creating a gallery of images using php and css. The images are placed in an unordered list as shown below: <ul style="list-style-type:none;"> <? while($data=mysql_fetch_row($result)) { $pic=$data[2]; if ($pic) { $ ...

CSS magic: Text animation letter by letter

I have a <div> with text. <div> to be revealed on the page one character at a time:</p> <div>, the animation should stop and display the full text instantly.</p> In summary, I aim to replicate an effect commonly seen in Jap ...

Encountering a malfunction in executing the AngularJS controller file

In the project run with http-server and node.js, the angular controller is unable to connect with index.html. classifieds.js (function() { "use strict"; angular .module("ngClassifieds") .controller("ClassifiedsCtrl", ['$scope', ...

Add a square div in every direction around the existing content in an HTML file

Begin by locating square number 1. Once you press the + symbol above square 1, square 2 will appear. From there, you can click the + on the right side of square 2 to reveal square 3. Is it possible to achieve this sequence? If so, what is the best way to ...

Creating a personalized pivot-table using the WebDataRock Javascript library with a unique configuration based on a

I'm having trouble getting this demo to work with the "hierarchy" parameter. Even when I specify the parameter value, it seems to apply the condition to the entire hierarchy chain. "conditions": [{ "formula": "#val ...

Best practices for securing passwords using Chrome DevTools in React development

React developer tool inspector Is there a way to prevent password values from appearing in the inspector as a state when handling form submissions in ReactJS, especially when using Chrome's React developer tool? ...

Waiting for Selenium in Javascript

I'm having trouble using Selenium Webdriver with Node.js to scrape Google Finance pages. The driver.wait function is not behaving as expected. I've configured my Mocha timeout at 10 seconds and the driver.wait timeout at 9 seconds. The test passe ...

What is the process for incorporating an additional input in HTML as you write?

I am looking to create a form with 4 input boxes similar to the layout below: <input type="text" name="txtName" value="Text 1" id="txt" /> <input type="text" name="txtName2" value="Text 2" id="txt" /> <input type="text" name="txtName3" valu ...

What is the process of implementing a page change using a GET request in JavaScript using Node.js and Express?

Within this application, users are provided with a table where they can input data. Each row in the table is equipped with an "Edit" button that, when clicked, should redirect them to a new page labeled "/update" where modifications to the specific row can ...

Using Selenium with JavaScript and Python to simulate key presses

Is there a way to simulate key presses as if typing on a keyboard? I am looking to programmatically click on an input element and then emulate the user typing by pressing keys. I prefer not to use XPath selectors combined with sendkeys or similar methods. ...

Should I use an array literal or split a string?

Imagine you are in need of a predetermined list of words (the focus here is not on the debate surrounding hard-coding). Would you choose this approach: var items = 'apple banana cherry'.split(' '); Or do you favor this alternative: ...

Loading views and controllers on-the-fly in AngularJS

A new configuration tool is under development using Angular.JS. The user interface consists of two main sections: a left panel with a tree view listing all the configuration items and a right panel displaying screens for editing these items. There are appr ...

Using the object value to map an array and populate the resulting elements

i have a function const [jobs, setJobs] = useState([]) const addJob = (title, role) => { const newJobs = [...jobs, { title, role}] setJobs(newJobs) } whenever a form is submitted, the addJob function creates state data containing ...

Enhance your web design with the latest Bootstrap 5.2

I attempted to implement a tooltip using jquery in my jquery datatable, but unfortunately the tooltip is not appearing. Below is the code snippet: render: function (data, type, row, meta) { var total = row.success + row.error; if (row.isConsumed = ...

Having trouble with the express message! I can't seem to access the template I created

I am looking to receive a notification similar to an alert, as described in this link: https://github.com/visionmedia/express-messages By default, I receive something like this https://i.stack.imgur.com/9XlA9.png If I use a template, I do not get any out ...