Skip to content Skip to sidebar Skip to footer

Change Color Of Button During Keypress

I want to change the color of a when it is clicked by a mouse or while pressing the enter key. To change the color when clicked by mous

Solution 1:

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>

Solution 2:

Try This

.clicked{
background:#fff !important;
}

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

Solution 3:

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','');
              }
            });

Post a Comment for "Change Color Of Button During Keypress"