Dejsa Cocan
Dejsa Cocan

Reputation: 1569

Toggle certain divs to be visible or hidden based on which button is clicked

I'm still getting into jQuery, so I am probably making this harder than it needs to be. What I want to do is make it so that, when one button is clicked, only one div should be set to be visible.

For example, when the .Dist button is clicked, only the div called "Products" should be set to visible. When the .Market button is clicked, only the div called "Apps" should be visible. When the .Services button is clicked, then only the div called "ServiceSec" should be visible.

What I have now mostly works...but what happens is that two or more of the divs can be displayed at once (i.e. If I don't hit the .Dist button again to close the "Products" div then go click on the .Market button, then the "Markets" div content will be displayed as well.)

jQuery.noConflict();
(function ($) {
  $(document).ready(function () {
   if ($(".Dist").click(function (e) {
        $(".Products").toggle();
    }));
    if ($(".Market").click(function (e) {
        $(".Apps").toggle();
    }));
   if($(".Services").click(function (e) {
        $(".ServiceSec").toggle();
    }));
  });
})(jQuery);

Is there a way I can easily add/remove a class to each of the three divs ("Products," "Apps," and "ServiceSec") so that they display only when the correct button is clicked?

Upvotes: 0

Views: 329

Answers (2)

Noobie3001
Noobie3001

Reputation: 1251

This should work..

<button type="button" id="dist">Products</button>
<button type="button" id="market">Markets</button>

<div class="products all">product1</div>
<div class="products all">product2</div>
<div class="apps all">app1</div>
<div class="apps all">app2</div>

<script type="text/javascript">
    $(document).ready(function () {       
        $('.all').hide();

        $('#dist').on('click', function (e) {
            $('.all').hide();
            $('.products').show();
        });

        $('#market').on('click', function (e) {
            $('.all').hide();
            $('.apps').show();
        });
    });
</script>

Upvotes: 1

tymeJV
tymeJV

Reputation: 104795

Give all of your div's a common class:

<div class="common Products"></div>
<div class="common Apps"></div>
<div class="common ServiceSec"></div>

And in your buttons, define a custom data attribute with the div to toggle as well as a common class:

<button class="commonBtn" data-div="Products">Click me</button>
<button class="commonBtn" data-div="Apps">Click me</button>
<button class="commonBtn" data-div="ServiceSec">Click me</button>

And one jQuery click event:

$(".commonBtn").click(function() {
    //hide any other common divs that may be showing
    $(".common").hide();

    //Show the div that is located in the data attribute
    var divClassToShow = $(this).data("div");
    $("." + divClassToShow).show();
});

Upvotes: 0

Related Questions