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

JavaScript code for transitioning between a thumbnail and a full-width image header on a webpage

I am looking to create transitions in NextJs that involve a smooth shift from a thumbnail image to a full-screen header when clicking on a project from the home page. I prefer utilizing internal routing rather than React Router, but I am open to using that ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

Error in Firefox: "Anticipated media feature name, but discovered 'hover'"

I am trying to style elements differently based on whether the client browser supports hovering or not. I came across media features as a solution and implemented it in the following way: /* Supports hovering */ @media (hover: hover) { ... } /* Does not ...

Manage the border around the image by incorporating a timer countdown - starting from a complete circle, transitioning to a partial arc, and finally disappearing completely

My expertise lies in html, css, and angularjs for front-end development. I have an image that is initially surrounded by a thick border forming a full circle. As a countdown of one minute begins, I want the border to gradually disappear as time progresses. ...

Tips for updating the current user's username value in local storage in Angular

https://i.stack.imgur.com/ZA32X.png https://i.stack.imgur.com/iDHZW.png I am facing an issue with updating the local storage of a current User for only username. When I update the username, it's not reflecting in local storage. Even though I can s ...

Is there a way to dynamically access BEM-style selectors using CSS modules?

For instance, I have this specific selector in my App.module.css file: .Column--active I want to access this selector from the App.js file in React using CSS modules. After importing all selectors from the CSS file as import styles from './App. ...

Position the second line of text to align in MUI

I am facing an issue with aligning the text on the second line. It should match up with the text on the first line. For reference, you can check out the Codesandbox by CLICKING HERE <Card sx={{ maxWidth: 200 }}> <CardMedia component="i ...

Showing an image on Angular JS only for certain input values

To create the desired program, make sure to input the following specifications: File size field – 300x250 or 728x90 File extension field – gif <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> &l ...

Using Vanilla JavaScript and VueJS to smoothly scroll back to the top of a div when a button is clicked

I have a VueJS-based app that features a multistep form with a next button. You can check out the functioning of the app here: My current challenge is ensuring that once the user clicks the next button, the top of the following question becomes visible. I ...

Focus on the input field automatically

In my code, there are instances where I use the following: <input data-ng-disabled="SOME_SCOPE_VARIABLE" /> Additionally, I would like to have the option to use it in this way as well: <input data-ng-autofocus="SOME_SCOPE_VARIABLE" /> Alter ...

Experimenting with Selenium to automate processes involving dynamic class attributes

My issue involves a Button class = "searchbar__SearchButton-sc-1546roh-3 searchbar__CancelButton-sc-1546roh-4 glEceZ" I am attempting to locate this element in the browser using return browser.element('button[class^="searchbar__CancelButton-"]&ap ...

Change the data returned by Ajax

After making an ajax request, my table gets populated with data from my array. The return is as expected, but now I want to modify this data before displaying it to the user. Whether this modification happens before or after the data is placed in the table ...

What is preventing Javascript from executing a function when there is an error in another function?

Can you explain why a JavaScript function fails to run if there is an error in another function? Recently, I encountered an issue on my HTML page where the alert from the popup1() function would not load. It turns out the problem stemmed from an error in ...

Alter the border line's color based on the specific section or div it overlays

I am attempting to utilize jQuery in order to change the color of my border line depending on its position within the divs. I have set the position to absolute and it is positioned on both divs. My goal is to make the line on the top div appear as grey, wh ...

I am looking to design an AngularJS directive that will generate an interactive HTML template featuring a button

var ImagesApp = angular.module('Images', []); ImagesApp.directive('fancybox', function($q, $http, $templateCache) { return function(scope, element, attrs) { scope.ShowFullImageByClick = function() { var el = '<label ...

What is the best way to develop a card stack swiper similar to Tinder using React?

After experimenting with various packages, I found that none were satisfactory for creating a customizable card swiper. As a result, I am now considering developing my own solution. What would be the best approach for adding animations, enabling draggable ...

Methods for delivering static resources on multiple routes in Express JS

Is there a way to effectively serve static resources for all routes in Express JS? I attempted to serve files with static resources using the following code snippet: app.use(Express.static(`${this.PATH}`)); app.use(Cors()); app.use(Express.json()); app.g ...

Navigating through Sails.Js: A Guide to Implementing Pagination

Looking to implement paginated tables in your application using sails.js, mongodb, and waterline-ORM? Wondering if there is a recommended method for pagination in sails.js? ...

Creating a dynamic interaction between HTML forms and JavaScript using the onsubmit event handler

Having trouble getting my JavaScript file to fire when clicking the submit button on my simple HTML form. Can anyone provide some assistance? **UPDATED CODES Here is a snippet of my condensed HTML file: <html> <form name="form01" id="form01" ac ...

Tips for ensuring all data is downloaded in Firebase (Firestore) Storage before proceeding?

I am currently developing a light dashboard in Vue that connects to Firestore and Storage. As someone who is not an expert, I have encountered a roadblock in what should be a simple task. The issue lies with a function that is meant to retrieve all URLs ba ...