jQuery/Javascript - perform an action while element is focused -
my goal automatically refresh entries every x seconds while textarea has focus on it. when user leaves automatic refresh removed.
i tried jquery on event not work expect.
what doing wrong?
$('#content_section').on('focus', '.reply-form textarea', function () { setinterval(refresh_data(this), 1000 * 1); }); var refresh_data = function (element) { if ($(this).attr('data-parent')) { $.ajax({ // create ajax call... data: {}, // form data type: "post", // or post url: "/e/comments/" + $(this).attr('data-parent') + "/", // file call datatype: 'json', success: function (response) { // on success.. if (response.parent) { $('article .comments[data-comment-list="' + response.parent + '"]').html(response.html); } } }); } };
you have store reference interval, , clear when input looses focus, , have use anonymous function setinterval if you're going pass arguments
$('#content_section').on({ focus: function () { var self = this; $(this).data('timer', setinterval(function() { refresh_data(self); }, 1000) ); }, blur: function() { clearinterval( $(this).data('timer') ); } }, '.reply-form textarea'); function refresh_data(element) { var parent = $(element).data('parent'); if ( parent ) { $.ajax({ data: $(element).closest('form').serialize(), type: "post", url: "/e/comments/" + parent + "/", datatype: 'json' }).done(function (response) { if (response.parent) { $('article .comments[data-comment-list="' + response.parent + '"]').html(response.html); } }); } };
Comments
Post a Comment