Reputation:
I have a photo galery with following simple function to navigate to the previous / next photo with the arrow keys on keyboard:
$(function() {
var navEnabled = true;
$(document).keyup(function(e) {
if (navEnabled) {
switch(e.keyCode) {
case 37 : window.location = $('.prev').attr('href'); break;
case 39 : window.location = $('.next').attr('href'); break;
}
}
});
$('#comment_area').bind('focus', function (event) {
navEnabled = false;
}).bind('blur', function (event) {
navEnabled = true;
});
});
Below each photo I have a html textarea element (! which is loaded via AJAX while page load!) with the id #comment_area to leave a comment to a photo, and I'm looking for a solution to disable the keyboard photo navigation while typing and turn on after again. The code above seems not to work, and I guess it's because the textarea element was loaded via AJAX. I tried to move the .bind function code into the AJAX request, so it will know about the #comment_area id, but then the navEnabled variable is unknown.
Upvotes: 1
Views: 223
Reputation: 28880
Use event delegation.
Let me assume that the container element that you're loading the Ajax content into is called #ajax_container
. Then you could use:
$('#ajax_container').on( 'focus', '#comment_area', function (event) {
navEnabled = false;
}).on( 'blur', '#comment_area', function (event) {
navEnabled = true;
});
And what version of jQuery are you using? This code is for 1.7+ and will need to be adjusted for older versions.
Upvotes: 1
Reputation: 50523
How about just not binding it to that specific element using not()
:
$(document).not('#comment_area').on('keyup', function(e) {
switch(e.keyCode) {
case 37 : window.location = $('.prev').attr('href'); break;
case 39 : window.location = $('.next').attr('href'); break;
}
});
Upvotes: 0