The problem is that your load
call destroys and recreates the textarea
, and nothing attaches the event handlers to the new textarea
. The handlers you're attaching only get attached to the original one, not the new replacement.
You can solve that with event delegation, since jQuery makes sure blur
and focus
bubble (even though they don't bubble natively on all browsers);
$(function () {
var timerId = 0;
$('#refresh').on('focus', 'textarea', function () {
clearInterval(timerId);
});
$('#refresh').on('blur', 'textarea', function () {
timerId = setInterval(function () {
$('#refresh').load('test.php #refresh');
}, 1000);
});
});
That hooks the events on the #refresh
element, but fires the handlers only if the event originated in a descendant textarea
of it.
Or since there's no reason to be looking up refresh
repeatedly:
$(function () {
var timerId = 0,
refresh = $("#refresh");
refresh.on('focus', 'textarea', function () {
clearInterval(timerId);
});
refresh.on('blur', 'textarea', function () {
timerId = setInterval(function () {
refresh.load('test.php #refresh');
}, 1000);
});
});
Note that the change also means only textarea
elements within the #refresh
div
get the events, whereas with your original code, all textarea
elements on the page got it.