I’d like to make a two-in-one solution for keypress event.
If I hit enter, and no form elements are active in my site I’d like to alert AAA.
Else submit the active form. How can i do this?
$(document).bind('keypress', function(e) {
if(e.keyCode==13){
e.preventDefault();
alert("AAA");
}
}); // the enter key hitted and alerted AAA
But how can i check the form’s state? It’s a simple mailsender form with 4 fields, 3 input 1 textarea.
By Raj’s comment here is the good solution for this:
jQuery.fn.fadeToggle = function(speed, easing, callback) {
return this.animate({opacity: 'toggle'}, speed, easing, callback);
};
var hotkeys = true;
$(document).bind('keypress', function(e) {
if((e.keyCode==13) &&(hotkeys == true)){
e.preventDefault();
$("#boxforfadein").fadeToggle();
}
});
$("form *").live("focusin", function(){
hotkeys = false;
console.log("hotkeys off");
return hotkeys;
});
$("form *").live("focusout", function(){
hotkeys = true;
console.log("hotkeys on");
return hotkeys;
});
Use focus and focusout to keep track of whether your form has focus and display the appropriate alert.
There is also document.activeElement but I am not too sure if all browsers support it