You have several issues with your code. First, you're missing a closing bracket }
in your if/else statement. Check your console, F12 to see the error:
Uncaught SyntaxError: Unexpected end of input
Secondly, as noted above in the comments, className
doesn't automatically exist and doesn't change the classes of the elements. className
is a property of the DOM object. You'll need to get the clicked element and reference the className
property to retrieve and set this correctly.
Before you can do that however, you need to get the clicked element. To do this, add the event
parameter to your inline click handler:
onclick="toggleClass(event);"
and reference the event object in your function toggleClass
:
function toggleClass(evt) {
Use the target
property of the event
object to find the clicked element and save it off into a variable:
var btn = evt.target;
Finally, reference btn.className
in place of all of the className
references you have in your function.
DEMO:
function toggleClass(evt) {
var btn = evt.target;
if(btn.className == "button button1") {
btn.className = "info";
} else {
btn.className = "button button1";
}
}
div {
color: #fff;
}
div.button.button1 {
background: blue;
}
div.info {
background: green;
}
<div class="button button1" onclick="toggleClass(event);">Stay Updated</div>