cgee
cgee

Reputation: 1897

fade two or more divs one by one after clicking a button

I want to fade out the first div and fade in the next div.

If I click in the second div a button the second div should fade out and the third div should fade in.

I try this JS:

    $(function () {
        var fragen_gesamt = $('.dmd-container-frage').length;
        $('.dmd-container-frage').hide();
        $('.dmd-container-frage:first-child').show();
        $('.btn').on('click', function () {
            $('.dmd-container-frage:first-child').fadeOut(500, function () {
                $(this).next('.dmd-container-frage').fadeIn(1000);
            });
        });
    });

But it's fading only to the second div.

https://jsfiddle.net/neo3d0m2/

Upvotes: 0

Views: 170

Answers (1)

t1m0n
t1m0n

Reputation: 3431

You need to change selector in you click function. Now you finding first block, and fadein next (which is second), what you need is to find parent of clicked button and do rest of logic according to this element:

    $(function() {
      var fragen_gesamt = $('.dmd-container-frage').length;
      $('.dmd-container-frage').hide();
      $('.dmd-container-frage:first-child').show();
      $('.btn').on('click', function() {
        $(this).closest('.dmd-container-frage').fadeOut(500, function() {
          var $el = $(this).next('.dmd-container-frage');
          // Check if there is next element
          if ($el.length) {
            $(this).next('.dmd-container-frage').fadeIn(1000);
          } else {
            alert('done!')
          }

        });
      });

    });

Check out this fiddle - fiddle

Upvotes: 2

Related Questions