fja3omega
fja3omega

Reputation: 222

Simplify jquery slideup loop

I am currently working on a text slider using jquery.

The code relies on slide toggle and fade working together.

The sample code is here https://codepen.io/fja3omega/pen/GwVYXM

My jQuery is:

jQuery( document ).ready(function() {
    jQuery.fn.slideFadeToggle  = function(speed, easing, callback) {
        return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
    }; 
    var counted = 1;
    jQuery(".slidem").find( "#rotate1" ).slideFadeToggle();
    setInterval(function(){
        counted = counted + 1;
        torotate = "#rotate" + counted;
        if(counted!=5) {
            jQuery(".slidem").find( torotate ).slideFadeToggle();
        } else {
            counted = 1;
            jQuery(".slidem .rotater" ).show();
            jQuery(".slidem").find( "#rotate1" ).slideFadeToggle();
            jQuery(".slidem").find( "#rotate5" ).show();
        }
    }, 3000);
});

I was wondering if there was a way to shorten or simplify the jQuery.

Upvotes: 1

Views: 309

Answers (1)

Kosh
Kosh

Reputation: 18423

Yes, you can simplify and improve your code removing all the unnecessary id and class attributes. Also you might make your code more abstract to support any number of "slides" not only 5.

See the snippet below:

jQuery(document).ready(function() {
  jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
  };
  var n = 0, slides = jQuery('.slidem > div');
  (function slide() {
    n = n * (n < slides.length) || +!slides.show();
    slides.eq(n++).slideFadeToggle();
    setTimeout(slide, 1000);
  })()
});
.irotate {
  text-align: center;
  margin: 0 auto;
  padding: 10% 0;
  display: block;
}

.thisis {
  display: inline-block;
  vertical-align: middle;
  height: 20px;
}

.slidem {
  overflow: hidden;
  text-align: center;
  min-width: 90px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="irotate">
  <div class="thisis">This is a&nbsp;</div>
  <div class="thisis slidem">
    <div>&nbsp;</div>
    <div>simple</div>
    <div>super easy</div>
    <div>fun</div>
    <div>working</div>
  </div>
  <div class="thisis">&nbsp;Text Slider</div>
</div>

Upvotes: 1

Related Questions