Huma Ali
Huma Ali

Reputation: 1809

jQuery selector for same classes

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

Upvotes: 7

Views: 102

Answers (3)

SiMag
SiMag

Reputation: 596

That's because when you click the "show more" of the right side the var click is true. You can store the click attribute in jQuery.data

$(".OffersContainer > span").click(function(){
    var click = $.data(this, "click") || false;
    $(this).siblings(click ? "div:gt(0)" : "div:lt(3)").slideDown(); 
    $.data(this, "click", true);
});

Demo

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

Upvotes: 1

dfsq
dfsq

Reputation: 193261

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/

Upvotes: 4

Related Questions