Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse animation on every second click?

I have 6 "blocks" and each contains different texts, for the sake of simplicity let's just consider these as my "blocks"

<div id="block1"> <h2> Block1 </h2> </div

I have 3 of them visible and 3 hidden. I have a button which replace the corresponding blocks

$(".showmore").click(function(){

    $("#block1").fadeOut("slow", function(){
        $(this).replaceWith($("#block4").html());
        $(this).fadeIn("slow");
    });

    $("#block2").delay(400).fadeOut("slow", function(){
        $(this).replaceWith($("#block5").html());
        $(this).fadeIn("slow");
    });

    $("#block3").delay(800).fadeOut("slow", function(){
        $(this).replaceWith($("#block6").html());
        $(this).fadeIn("slow");
    });

    $(this).text('Show less');

});

It works fine but have no idea how to revert it. I tried to clone the elements to a variable and then load them but it seems like the id is gone because when I try to hide the block1 or the block4 none of them disappear. Can anyone help?

like image 704
Paralyz3d Avatar asked Aug 22 '16 10:08

Paralyz3d


Video Answer


1 Answers

As i understood, you have 3 div's that you would like to revert them back to the content they had after a fadeout/fadein event on the click of another div. The issue on your try is the usage of the replaceWith method. Is this what you are looking for to achieve? See fiddle here.

$(".showmore").click(function(){
    $("#block1").fadeOut("slow", function(){
        //save the content of the hidden block to a variable
          var html = $("#block4").html();
        //put the content of the current div to the hidden div, to be used on the next click
        $("#block4").html($(this).html());
        //show the content of the hidden div
        $(this).html(html);
        $(this).fadeIn("slow");
    });

    $("#block2").delay(400).fadeOut("slow", function(){
        var html = $("#block5").html();
        $("#block5").html($(this).html());
        $(this).html(html);
        $(this).fadeIn("slow");
    });

    $("#block3").delay(800).fadeOut("slow", function(){
        var html = $("#block6").html();
        $("#block6").html($(this).html());
        $(this).html(html);
        $(this).fadeIn("slow");
    });

    $(this).text('Show less');

});

As you see, i copy the content of a div to the corresponding hidden one. Like this you can basically switch the data on each click.

like image 121
avi Avatar answered Sep 29 '22 12:09

avi