Luca Antonelli
Luca Antonelli

Reputation: 383

AJAX Call - Flickering more for each click

I'm building a chart (in Yii2 Framework) that can show different report for each period, i need to update the chart if the user click on the button group with 7D-1M-1Y.

The update work, but every time i change the view period with button click, the flicker times before the right chart is shown, becomes higher.

This is my JS:

if(!$('#7D').hasClass('active') && !$('#1M').hasClass('active') && !$('#1Y').hasClass('active')) { $('#1M').addClass('active'); }
$('#7D').click(function() {
    var myValue = "7D";
    $.get("",{val:myValue},function(data){
        $('.btn').removeClass('active');
        $('#7D').addClass('active');
        $('#w2').fadeOut('fast', function(){
            $('#w2').html(data).fadeIn('fast');
        });
    });
});
$('#1M').click(function() {
    var myValue = "1M";
    $.get("",{val:myValue},function(data){
        $('.btn').removeClass('active');
        $('#1M').addClass('active');
        $('#w2').fadeOut('fast', function(){
            $('#w2').html(data).fadeIn('fast');
        });
    });
});
$('#1Y').click(function() {
    var myValue = "1Y";
    $.get("",{val:myValue},function(data){
        $('.btn').removeClass('active');
        $('#1Y').addClass('active');
        $('#w2').fadeOut('fast', function(){
            $('#w2').html(data).fadeIn('fast');
        });
    });
});

This is my Button Group:

<?= ButtonGroup::widget([
    'buttons' => [
        ['label' => '7D', 'id' => '7D'],
        ['label' => '1M', 'id' => '1M'],
        ['label' => '1Y', 'id' => '1Y'],
    ],
]); ?>

TIP: I tried with body instead of #w2 (the id of the chart), and it works properly without increments the flickering time, but flicker one time vertically, when the chart diseppear the page go to the top and then return to the new bottom.

Solve this can also be helpful, i only need a solution, is not important how

Upvotes: 4

Views: 872

Answers (1)

Kiran Shahi
Kiran Shahi

Reputation: 7980

As per your question, I think your click event has been attached to your element for multiple times. To avoid attaching them several times you can use

$("#SomeId").off("click").on("click", function({
    // Your logic here.
})); 

Though the problem on question is not clear.

Upvotes: 5

Related Questions