简体   繁体   中英

Toggling three divs with one

What I'm doing: I have three DIVs, each of them acting as a button to swap one div with different content.

[BOX_1] [BOX_2] [BOX_3] [--------BOX_4------------]

For instance: If you click BOX_1, it swaps BOX_4 out with BOX_1_CONTENT & (Clicking BOX_1 again returns it to BOX_4) If you click BOX_2, it swaps BOX_4 out with BOX_2_CONTENT & (Clicking BOX_2 again returns it to BOX_4) If you click BOX_3, it swaps BOX_4 out with BOX_3_CONTENT & (Clicking BOX_3 again returns it to BOX_4)

BOX_1_CONTENT, BOX_2_CONTENT, and BOX_3_CONTENT are all set to display:none; and appear after clicking.

What Works: It works great if you are only toggling back and forth (ie toggling content by clicking the BOX_1 back and forth).

My problem: I am having trouble dealing with Clicking BOX_1 and then before toggling back, clicking BOX_2 or BOX_3.

It seems I need a way to deal with scenarios such as: Click BOX_1 (swapping BOX_4 with BOX_1_CONTENT) and then immediately clicking BOX_3 and having it swap BOX_1_CONTENT with with BOX_3_CONTENT.

Any suggestions on a better way to do this?

<script>
$(document).ready(function(){
    $(".BOX_1").click(function()
    {        
        $('.BOX_4, .BOX_1_CONTENT').fadeToggle("slow");
    });

        $(".BOX_2").click(function()
    {        
        $('.BOX_4, .BOX_2_CONTENT').fadeToggle("slow");
    });

        $(".BOX_3").click(function()
    {        
        $('.BOX_4, .BOX_3_CONTENT').fadeToggle("slow");
    });

});
</script>

is this what your looking for :

HTML:

    <div class="BOX_1">BOX 1</div>

<div class="BOX_2">
BOX 2
</div>

<div class="BOX_3">
BOX 3
</div>

<!-- data-content is to check do we have content or which boxes's content do we hv now -->
<div class="BOX_4" data-content="">BOX 4 (CONTENT TO BE REPLACED)</div>

<div class="BOX_1_CONTENT">CONTENT FOR BOX 1</div>
<div class="BOX_2_CONTENT">CONTENT FOR BOX 2</div>
<div class="BOX_3_CONTENT">CONTENT FOR BOX 3</div>

JS:

$(document).ready(function(){
   var b4c = $('.BOX_4').html(); // content of box 4 so that we cn refer to it later
    $(".BOX_1,.BOX_2,.BOX_3").click(function()
    {
      var active_content =  $(".BOX_4").data('content');
      var cls = $(this).attr('class');
      if(active_content == '')
      {
       $(".BOX_4").html($("."+cls+'_CONTENT').html())
       $(".BOX_4").data('content',cls);
       }
       else
       {
         if(active_content == cls)
         {
            $('.BOX_4').html(b4c).data('content','');
          }
          else
          {
            $(".BOX_4").html($("."+cls+'_CONTENT').html())
                $(".BOX_4").data('content',cls);
          }
       }
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM