$(document).ready(function() {
('.button').click(function() {
let item = $(this).closest('item');
if (item.css.('display') === 'none') {
item.show();
item.css('display', 'block');
} else if (item.css.('display') === 'block') {
item.hide();
item.css('display', 'none');
}
});
});
.item {
display: none;
}
<div class="container">
<button class="button">Click</button>
<div class="front">front page</div>
<div class="item">
This is a paragraph with little content. This is another small paragraph.
</div>
</div>
Aim is to hide and show the current div on button click. i have the same container with the same class names. if i use simply toggle button, upon clicking the button, every other containers are toggled. In this case, only current container must show and hide. The class container's first div child is initally displayed and the second div child is hidden/ display:none. upon button click, the second div child is displayed, the display:none is change to display:block. Code here seems not working.
Use .siblings()
Given a jQuery object that represents a set of DOM elements, the .siblings() method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.
Working snippet:-
$(document).ready(function() {
$('.button').click(function() {
$(this).siblings(".item").toggle();
});
});
.item {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="button">Click</button>
<div class="front">front page</div>
<div class="item">
This is a paragraph with little content. This is another small paragraph.
</div>
</div>
Use parent()
to find current button click element and then find .item
class in that container and simply use fadeToggle()
to hide and show element as below.
$(document).ready(function(){
$('.button').click(function(){
$(this).parent().find(".item").fadeToggle();
});
});
.item{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="button">Click</button>
<div class="front">front page</div>
<div class="item">
This is a paragraph with little content.
This is another small paragraph.
</div>
</div>
<script>
$(document).ready(function(){
$(".button").click(function(){
$(".front").toggle();
$(".item").toggle();
});
});
</script>
<style type="text/css">
.item{display: none;}
</style>
<button class="button">Click</button>
<div class="front">front page</div>
<div class="item">
This is a paragraph with little content.
This is another small paragraph.
</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