Search code examples
jqueryfade

How to change show/hide to fadein/out?


The code was edited from show hide divs using Next Previous button using jQuery?

I would like to make a 1000ms fadein/out instead of the sudden show/hide but don't know how to do so.

Here is what I have so far: https://jsfiddle.net/xzk4patd/

HTML:

<div class="divs">
<div class="cls1"></div>
<div class="cls2"></div>
<div class="cls3"></div>
</div>

<div id="prev">Prev</div>
<div id="next">Next</div>

CSS:

.cls1{
    background: red;
    height: 200px;
    width: 200px;
}
.cls2{
    background: blue;
    height: 200px;
    width: 200px;
}
.cls3{
    background: green;
    height: 200px;
    width: 200px;
}
#prev{
    background: gray;
    height: 50px;
    width: 50px;
}
#next{
    background: orange;
    height: 50px;
    width: 50px;
}

javascript:

$(document).ready(function(){
    $(".divs div").each(function(e) {
        if (e != 0)
            $(this).hide();
    });

    $("#next").click(function(){
        if ($(".divs div:visible").next().length != 0)
            $(".divs div:visible").next().show().prev().hide();
        else {
            $(".divs div:visible").hide();
            $(".divs div:first").show();
        }
        return false;
    });

    $("#prev").click(function(){
        if ($(".divs div:visible").prev().length != 0)
            $(".divs div:visible").prev().show().next().hide();
        else {
            $(".divs div:visible").hide();
            $(".divs div:last").show();
        }
        return false;
    });
});

Solution

  • So I assume you want to achive s.th. like this:

    $(".divs > div").each(function (e) {
        if (e != 0) $(this).hide();
    });
    
    $("#next").click(function () {
        if ($(".divs > div:visible").next().length != 0) {
            $(".divs > div:visible").fadeOut(1000, function(){
                $(this).next().fadeIn(1000)
            });
        } else {
            $(".divs > div:visible").fadeOut(1000, function () {
                $(".divs > div:first").fadeIn(1000);
            });
        }
        return false;
    });
    
    $("#prev").click(function () {
        if ($(".divs > div:visible").prev().length != 0) {
            $(".divs > div:visible").fadeOut(1000, function(){
                $(this).prev().fadeIn(1000);            
            });
        } else {
            $(".divs > div:visible").fadeOut(1000, function () {
                $(".divs > div:last").fadeIn(1000);
            });
    
        }
        return false;
    });
    

    Note that .fadeIn() (and .fadeOut()) supports a callback-function, which will trigger if the animation is completed. Otherwise your div will jump around, demonstrated here.

    If you want to float the divs underneath just remove the position:absolute. You can also set it to postion:relative.

    Demo