Reputation: 67
I have a div which animate only once when I press the j button, I want to animate the div each time when i press j button on my keyboard without refreshing the page.
is this possible using JQuery???
sorry for my bad english.
following is my code.
animate.html
<!DOCTYPE html>
<html>
<head>
<style>
.div {
width: 100px;
height: 100px;
background-color: red;
position: relative;
-webkit-animation-name: example; /* Chrome, Safari, Opera */
-webkit-animation-duration: 1s; /* Chrome, Safari, Opera */
animation-name: example;
animation-duration: 1s;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes example {
0% {background-color:red; left:0px; top:0px;}
50% {background-color:green; left:100px; top:100px;}
100% {background-color:red; left:0px; top:0px;}
}
/* Standard syntax */
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
50% {background-color:yellow; left:100px; top:100px;}
100% {background-color:yellow; left:0px; top:0px;}
}
</style>
</head>
<body>
<p>
<b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.
</p>
<br>
<div id="box"></div>
<script src="js/jquery-1.10.1.min.js"></script>
<script src="js/jquery.hotkeys.js"></script>
<script>
$(document).bind('keydown', 'j', function(){
$('#box').addClass("div");
});
</script>
</body>
</html>
Upvotes: 0
Views: 186
Reputation: 1316
It looks like the problem to me is that you aren't removing the class=div
after the animation is over. In This Fiddle, I added an event that fires when the CSS animation ends:
//fires when 'j' key is pressed
$('body').on('keydown', function (e) {
if (e.which == 106 || e.which == 74) {
$('#box').addClass("div");
}
});
$('#box').on('webkitAnimationEnd oanimationend msAnimationEnd animationend',
function (e) {
$('#box').removeClass("div");
});
This code works for me in Chrome 44 and FireFox 39, but I just tested it in IE10, and it didn't seem to work at all. Didn't even want to fire the initial keydown
event. I think the general idea is still true though. If you want the animation to repeat, you will have to remove the .div
class after the animation ends, so that you can add it again on keydown
.
EDITED fixed event to fire on 'j' not 'r' in my fiddle.
Upvotes: 0
Reputation: 1097
$(document).on("keydown", function (e) {
var key = e.keyCode;
if(key==74 || key==106){
$('#box').addClass("div");
}
});
Upvotes: 0
Reputation: 2031
you have to remove the class each time and add class again to you div
, here is the fiddle -
http://jsfiddle.net/hwu1z7dh/1/
Upvotes: 1
Reputation: 3297
Jquery has replaced 'bind' by 'on'.
Try this code:
$('body').on('keydown',function(e){
if(e.which==82 || e.which==106){
$('#box').addClass("div");
}
});
The ASCII value of 'J' is 82, and 'j' is 106.
Upvotes: 1