Tommy Pradana
Tommy Pradana

Reputation: 134

Event click fires multiple times after success get data

I have simple script like this:

(function($) {
    $(document).ready(function() {
        function getData() {
            $.ajax({
                url: '/path/to/file',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    var text = response.jsontitle;

                    $('#link').attr('class', '');
                    $('#link').attr('class', text);

                    // Second, Third, Fourth .... after get data
                    // Click fires 2, 3, 4 .... after get data
                    $('#link').on('click', function() {
                        console.log($(this).attr('class'));
                    })
                }
            });
        }

        var refreshData = setInterval(getData, 5000);

        getData();
    });
})(jQuery);

I want the click event to occur only once per time interval. Currently, however, the click event occurs as many times as getData() occurs.

For example, if the getData() occurs twice, then click event will happen twice as well.

Upvotes: 0

Views: 476

Answers (1)

Girish
Girish

Reputation: 12127

first unbind event then bind, if you want to use inside success callback function

$('#link').off('click').on('click'....

OR better to bind event once outside of callback function

Upvotes: 6

Related Questions