Cameron M Cameron M - 2 months ago 11
Javascript Question

Changing CSS attribute using toggleClass() on an input button

I have a red button, and I'd like to change it to a white button with a red outline when clicked, and then back to full red when clicked again. I cannot get it to change when clicked. It just stays red.

I'd like to be able to use "toggleClass()", the jquery function, to apply a class to the button with custom (background color) attributes. It uses the ".buttonF" CSS attribute, but will not apply the ".off" CSS attribute, as it would appear the class is not getting turned on by "toggleClass()"

The button toggles text appearing on the page, but that's not relevant to my issue.

Here is my HTML page:

<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="ryft1.css">
<script src=""></script>


function toggleF(button){
$(this).toggleClass("off"); <!-- Toggle background color by changing class-->

var f = document.getElementsByClassName("key");
var i;

for(i=0; i<f.length; i++){

else if(document.getElementById("1").name=="ON"){
for(i=0; i<f.length; i++){


<form action="">

<input type="button" class="buttonF" id="1" value="F"
onclick="toggleF(this);" name="ON">

<p class="key">Sample text</p>


Here is my CSS page:

.buttonF {
background-color: #ff0000;
padding: 13px 15px;
font-size: 12px;
border-radius: 50%;
border: 2px solid #ff0000;

background-color: #ffffff


You need to select the button in your function. this is not pointing to the element, but to the window object. Your element's this is the argument from your function.

Change this line:


To this: