简体   繁体   中英

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM