I want to change the color of a
when it is clicked by a mouse or while pressing the enter key.<
Try This
.clicked{
background:#fff !important;
}
$('.button').keydown(function(e){
if(e.which == 13){
$(this).addClass('clicked');
}
e.preventDefault();
});
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','');
}
});
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>