I have several divs inside a OffersContainer
div. On Page load I show only the First div of OffersContainer
. Then upon clicking the 'show more', I show first three divs and finally on clicking 'show more' for the second time I show all the divs.
Problem is I have two OffersContainer
at a time. And I want these two OffersContainer
div independent of each other. What actually happens is, when for the first time I click on left OffersContainer's
show more it behaves perfectly i.e show 3 divs. But now when I click show more of right side OffersContainer's div it will show all instead of showing first 3 divs. It means its not working independently of the other div? How can I make it run separately?
P.S: For some reason both of these divs will have same class OffersContainer
so I can't change the name. What am I doing wrong? Am I using wrong selectors?
Here is the Fiddle
And Here is the Fiddle with just one OffersContainer div just in case anyone wants to see
To select elements by a given class name, you use the getElementsByClassName() method: let elements = document. getElementsByClassName('className');
Answer: Use the jQuery each() Method You can simply use the jQuery each() method to loop through elements with the same class and perform some action based on the specific condition.
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
Don't store click information in shared global varibale. Instead you can persist it in the class name for each span:
$(".OffersContainer > div:gt(0)").hide();
$(".OffersContainer > span").click(function() {
$(this).siblings($(this).hasClass('click') ? "div:gt(0)" : "div:lt(3)").slideDown();
$(this).addClass('click');
});
Demo: https://jsfiddle.net/qo55rmuy/2/
You can use CSS to hide the relevant div
elements on initial load. This will solve the issue of the contents of the other .OfferContainer
elements being completely hidden.
.OffersContainer > div:nth-child(n+2) {
display: none;
}
From there you can change the logic so that it is keyed on the number of visible elements, instead of the click
variable, like this:
$(".OffersContainer > span").click(function() {
var $siblings = $(this).siblings();
var visibleLength = $siblings.filter(':visible').length;
$siblings.filter(visibleLength != 1 ? "div:gt(0)" : "div:lt(3)").slideDown();
});
Updated fiddle
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