2

I want to change the background color of a button permanently after it is clicked. Using the following code the color only changes while the button is active/being clicked. Once the mouse button is released the added "clicked" class is no longer applied to the element.

Applying the following code to an INPUT tag instead of a BUTTON tag works the way I need it to. However, I'm using a BUTTON tag since I want the value to be different from the text inside the button.

What do I need to change?

-- Thanks.

 HTML
 <button class="inactive" value="test">Button</button>

 CSS
 .inactive {background-color:gray;}
 .clicked {background-color:orange;}

 JS
 $(document).ready(function(){
      $('button').click(function(){
           $(this).addClass('clicked');
      });
 );
3
  • 2
    I can't replicate your problem: jsfiddle.net/9AT48 Commented Jun 13, 2013 at 16:18
  • 1
    This works fine in a fiddle. My guess would be that you have other CSS which you've not included which is interfering with this jQuery. Commented Jun 13, 2013 at 16:20
  • I found the problem. The button tag was inside a form element and was submitting and reloading the page upon being clicked. I didn't realize buttons submitted by default. Thanks for your help. Commented Jun 13, 2013 at 16:31

3 Answers 3

7

The only problem is that you are missing a curly brace: http://jsfiddle.net/AaKuf/

 $(document).ready(function(){
      $('button').click(function(){
           $(this).addClass('clicked');
      });
 }); //<==here
Sign up to request clarification or add additional context in comments.

Comments

1
$('button.inactive').click(function() {
    $(this).removeClass('inactive').addClass('clicked');
});

Should do the trick. This will clear the old class away from the button and give it the proper .clicked class. If the colour is resetting after using this solution, then the problem is elsewhere in your code.

Comments

0
$('button').mouseup(function() { 
    $(this).removeClass('clicked').addClass('inactive');
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.