0

I have a simple script, where the user can load two different containers which have some different content in them.

This is the code:

<div id="t-loader"></div>


<div class="media load-fixed active"> 
    Load Fixed
</div>
<br />
<div class="media load-extra"> 
    Load Extra
</div>



<br />
<div class="fixed-ads">
FIXED ADS IN HERE!!         
</div>


<div style="display: none;" class="extra-ads">
EXTRA ADS IN HERE!! 
</div>

And the jQuery:

$('.load-extra').click(function() {
    $(this).addClass('active');
    $('.load-fixed').removeClass('active');
    $('.fixed-ads').hide();
    $('#t-loader').show().html('loader');

    setTimeout(
      function() 
      {
        $('#t-loader').hide();
        $('.extra-ads').show();
      }, 2000);


});
$('.load-fixed').click(function() {
    $(this).addClass('active');
    $('.load-extra').removeClass('active');
    $('.extra-ads').hide();
    $('#t-loader').show().html('loader');
    setTimeout(
      function() 
      {
        $('#t-loader').hide();
        $('.fixed-ads').show();
      }, 2000);
});

The problem is, whenever someone clicks .load-extra AND .load-fixed both will be shown in at the page.

How can I do, so whenever someones either clicks .load-extra or .load-fixed, only one of them will show?

I have created a jsFiddle here: http://jsfiddle.net/j21oofwx/

In the example, try to click on "Load Extra" and "Load Fixed" quickly after each other - you'll see that content from both containers will be shown.

oliverbj
  • 5,771
  • 27
  • 83
  • 178
  • Just remove the setTimeout and put all the code outside from it. – Kundan Singh Chouhan Aug 31 '14 at 16:20
  • possible duplicate of [How do you handle multiple instances of setTimeout()?](http://stackoverflow.com/questions/315078/how-do-you-handle-multiple-instances-of-settimeout) – iabw Aug 31 '14 at 16:27

1 Answers1

4

The simplest way with your existing code is probably saving the setTimeout and clearing it each time a button is clicked - http://jsfiddle.net/uegt5opm/

var setTimer = null;
$('.load-extra').click(function() {
    $(this).addClass('active');
    $('.load-fixed').removeClass('active');
    $('.fixed-ads').hide();
    $('#t-loader').show().html('loader');

    clearTimeout(setTimer);
    setTimer = setTimeout(function(){
        $('#t-loader').hide();
        $('.extra-ads').show();
    }, 2000);


});
$('.load-fixed').click(function() {
    $(this).addClass('active');
    $('.load-extra').removeClass('active');
    $('.extra-ads').hide();
    $('#t-loader').show().html('loader');

    clearTimeout(setTimer);
    setTimer = setTimeout(function(){
        $('#t-loader').hide();
        $('.fixed-ads').show();
    }, 2000);
});

It's unusual to use setTimeout for this UI purpose in a 'real' setting though, so I wouldn't be surprised if this didn't transfer to your actual use case.

iabw
  • 1,108
  • 1
  • 9
  • 24