Adam
Adam

Reputation: 29039

Change color of button during keypress

I want to change the color of a

<input type='button' class='button'>

when it is clicked by a mouse or while pressing the enter key.

To change the color when clicked by mouse I can simply use the following css

.button:active{
   background-color:#FFF;
}

For the enter key, I tried the following jQuery code:

$('.button').keypress(function(e){
      if(e.which == 13){
          $(this).css('background-color','#FFF')
      }
  });

But this doesnt work, now the background remains white after hitting return. However, I only want the background to get white during the time someone hits enter. How can I achive this?

Upvotes: 1

Views: 5267

Answers (3)

Alpesh Jikadra
Alpesh Jikadra

Reputation: 1722

Please try following code

           $('.button').keypress(function(e){
              if(e.which == 13){
                  $(this).css('background-color','#FFF');
              }
            });

            $('.button').keyup(function(e){
              if(e.which == 13){
                  $(this).css('background-color','');
              }
            });

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78545

Use a combination of keypress/keyup to toggle the color:

$("button").keydown(function(e) {
    // Sets the color when the key is down...
    if(e.which === 13) {
    	$(this).css("background-color", "red");
    }
});
$("button").keyup(function() {
    // Removes the color when any key is lifted...
    $(this).css("background-color", "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Test
</button>

Upvotes: 2

SAGAR MANE
SAGAR MANE

Reputation: 685

Try This

.clicked{
background:#fff !important;
}

$('.button').keydown(function(e){
      if(e.which == 13){
           $(this).addClass('clicked');
        }
 e.preventDefault();
  });

Upvotes: 1

Related Questions