Reputation: 31
Here is my site: http://mttdn.com/dev/
If you click the light switch button in the top right, you will see that a hidden div slides in from the right. Click the button again, and it slides back. I want to be able to make that same action take place when the 'P' key is pressed. I am able to setup the .keypress();, which you can see if you click 'P', however, as you will also see, using the same code I did for the .click();, the div slides in, then slides out right away. I am trying to figure out how to use .toggle(); in conjunction with .keypress(); so that this doesn't happen.
Here is my code:
$(document).ready(function(){
var previewopen = $(".codepreview");
$(document).keypress(function(event){
if (event.which == 112){
previewopen.animate({left:"-=50%",},'normal');
previewopen.animate({left:"+=50%",},'normal');
}
});
});
I just want to be able to click 'P', have the div slide out and stop, then click 'P' again to have it slide back. What is the best way to accomplish this? Any help is greatly appreciated! Thanks!
Upvotes: 3
Views: 1515
Reputation: 237845
Just use a boolean switch:
(function() {
var on = false;
$(document).keypress(function(event) {
if (event.which == 112) {
previewopen.animate({left: on ? '-=50%' : '+=50%'}, 'normal');
on = !on;
}
});
})();
I have removed the trailing ,
in the object literal, which would cause a problem in some browsers (I'll let you guess which...), and I've used an anonymous function to keep on
local.
Upvotes: 2
Reputation: 19071
The click event seems to work fine. Why not trigger it on keypress ? Something like that:
$(document).ready(function(){
$(document).keypress(function(event){
if (event.which == 112){
$('.lightswitch').trigger('click');
}
});
});
Upvotes: 2