F
20

Spent 3 hours trying to make a simple button change color when you click it

I wrote a function in JavaScript and used 'onclick' in my HTML, but the button just turned grey and stayed that way (which was not the plan). I learned that I forgot to tell the function to change the color back after the first click. How do you make a button toggle between two colors properly?
3 comments

Log in to join the discussion

Log In
3 Comments
max_brown
max_brown5d ago
Forget the onclick attribute (it's kinda old school). Use addEventListener in your script to keep things tidy, and toggle a CSS class instead of messing with the style directly. That way you can control the look in one place.
8
foster.tessa
Totally agree with @max_brown, my coding bootcamp teacher drilled that exact method into us last week.
3
ward.kim
ward.kim5d ago
But what if @max_brown's way gets messy later?
3