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();
});
});
Bind the event on the div
s 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With