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?
4 comments

Log in to join the discussion

Log In
4 Comments
max_brown
max_brown2mo 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.kim2mo ago
But what if @max_brown's way gets messy later?
3
karencampbell
But how do you handle it when the app's got like 50 different event listeners floating around your script, don't they get tangled up?
1