Search code examples
jqueryslidetoggleslidedownslideup

Slide Up on click


I have several divs on my Page. On Page load I want only the First div visible with a 'Show more' link. Then upon clicking the 'show more', I want to load first three divs and finally on clicking it for the second time I want it to show all divs.

So far its working fine. But after show all, when the span tag is clicked, it should slide up and hide all except the first div i.e it should reset the divs as they were originally on Page load so that it gives the Show more/show less effect.

Here is the Fiddle


Solution

  • Try like this

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
    </script>
    
    <div class="OffersContainer">
    <div class='pan-box'>A</div>
    <div class='pan-box'>B</div>
    <div class='pan-box'>C</div>
    <div class='pan-box'>D</div>
    <div class='pan-box'>E</div>
    <span>Show more</span>
    </div>
    
    <script>
    $(".OffersContainer > div:gt(0)").hide();
    var click = false;
    var i = 1;
    $(".OffersContainer > span").click(function() {
        if (i <= 2) {
            $(this).siblings(click ? "div:gt(0)" : "div:lt(3)").slideDown();
            click = true;
        } else {
            $(this).siblings("div:gt(0)").slideUp();
            click = false;
            i = 0;
        }
    
        i++;
    });
    </script>