Efrin
Efrin

Reputation: 2423

jQuery/Javascript - perform an action while element is focused

My goal is to automatically refresh entries every x seconds while textarea has focus on it. When user leaves then automatic refresh is removed.

I tried with jquery on event but it does not work as I expect.

What I am 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 an AJAX call...
                data: {}, // get the form data
                type: "POST", // GET or POST
                url: "/e/comments/" + $(this).attr('data-parent') + "/", // the file to call
                dataType: 'json',
                success: function (response) { // on success..
                    if (response.parent) {
                        $('article .comments[data-comment-list="' + response.parent + '"]').html(response.html);
                    }
                }
            });
        }
    };

Upvotes: 1

Views: 1229

Answers (1)

adeneo
adeneo

Reputation: 318252

You have to store a reference to the interval, and then clear it when the input looses focus, and you have to use an anonymous function with setInterval if you're going to 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);
            }
        });
    }
};

Upvotes: 3

Related Questions