Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click function between multiple class names

I am new to jQuery and I am trying to write a .click() function in jQuery that is triggered from #buttons id to .hide() and .show() elements in #cards id.

For example, if I click on .blue div it should only show() .blueCard div and hide .redCard and greenCard

<div id="buttons">
    <div class="blue">Click Me!</div>
    <div class="red">Click Me!</div>
    <div class="green">Click Me!</div>
</div>

<div id="cards">
    <div class="blueCard blue"></div>
    <div class="redCard red"></div>
    <div class="greenCard green"></div>
</div>

This code seems a bit off... and not working!

$("#buttons").each(function(){
    var buttonColors = $("#buttons").attr("class").val();
    var cardColors = $("#cards").attr("class").val();

    buttonColors.on("click", function(){
        if ($(buttonColors + cardColors).length > 0) {
            carColors.show();
        } else {}
        carColors.hide();
    });
});
like image 714
alimarwan Avatar asked Oct 21 '25 14:10

alimarwan


1 Answers

Bind the event on the divs and get the class of the clicked element. Show only that one in #cards and hide others.

// Bind click event on all the <div>s inside #buttons
$('#buttons div').click(function() {
    // Get the classname of the clicked div
    var className = $(this).attr('class');
    
    // Show the respective div in cards
    // Hide others
    $('#cards .' + className).show().siblings().hide();
});
#buttons div {
  width: 100px;
  height: 100px;
  margin: 10px;
  float: left;
  color: white;
  text-align: center;
}
.blue {
  background: blue;
}
.green {
  background: green;
}
.red {
  background: red;
}

#cards {
  clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons">
    <div class="blue">Click Me!</div>
    <div class="red">Click Me!</div>
    <div class="green">Click Me!</div>
</div>

<div id="cards">
    <div class="blueCard blue">Blue</div>
    <div class="redCard red">Red</div>
    <div class="greenCard green">Green</div>
</div>
like image 51
Tushar Avatar answered Oct 23 '25 04:10

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!