Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a carousel using JavaScript

I am trying to make sliding DIVs.

I succeeded to make 1st DIV to go to 2nd DIV and vice versa. However, I could not make 2nd DIV slide to 3rd DIV.

The code is as follow :

$(function(){

  var slideW = $('#slides').width();
  
  // Next slide
  $('#next-slide').click(function( e ){
    e.preventDefault(); 
    $('#slides').animate({scrollLeft: slideW}, 600);
  });
  
  //previous slide
    $('#back-slide').click(function( e ){
    e.preventDefault();
    $('#slides').animate({scrollLeft: -slideW }, 600);
  });
  
});
#slides{  
  position:relative;
  overflow:hidden;
  margin:0 auto;
  background:#cf5;
  width:100%;
  height:200px;
  white-space:nowrap;
}
#slides div{
  position:relative;
  display:inline-block;
  margin-right:-4px;
  white-space:normal;
  vertical-align:top;
  *display:inline;
  background:#eee;
  width:100%;
  height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slides">
  <div>
    Content 1
    <a href="#" id="next-slide">Show Content 2 .. it works!</a>
  </div>
  
  <div>
  Content 2
    <a href="#" id="back-slide">Show Content 1 .. it works!</a>
    <br>
    <a href="#" id="next-slide">Show Content 3 .. not working!!</a>
  </div>
  
  <div>
  Content 3
    <a href="#" id="back-slide">Show Content 2 .. not working!!</a>
  </div>

</div>
like image 288
ALBADI Avatar asked Jan 25 '26 16:01

ALBADI


2 Answers

Carousel in vanilla JavaScript

Uses CSS display: flex to align elements and transition and transform to animate.
JS is used to increment/decrement the Current Slide index and set the parent's CSS transform:

const ELS = (sel, EL) => (EL || document).querySelectorAll(sel);
const EL = (sel, EL) => (EL || document).querySelector(sel);

const carousel = (EL_carousel) => {

  const EL_mover  = EL('.carousel-mover', EL_carousel);
  const ELS_slide = ELS('.carousel-slide', EL_carousel);
  const ELS_prev  = ELS('.prev', EL_carousel);
  const ELS_next  = ELS('.next', EL_carousel);
  const tot = ELS_slide.length;
  let c = 0; // Current slide index

  const anim = () => {
    EL_mover.style.transform = `translateX(-${c * 100}%)`;
  };

  const prev = () => {
    c -= 1;
    if (c < 0) c = tot - 1;
    anim();
  };

  const next = () => {
    c += 1;
    if (c > tot - 1) c = 0;
    anim();
  };

  ELS_prev.forEach(el => el.addEventListener("click", prev));
  ELS_next.forEach(el => el.addEventListener("click", next));

};

// Init carousel
ELS(".carousel").forEach(carousel);
.carousel {
  position: relative;
  overflow: hidden;
}

.carousel-mover {
  display: flex;
  background: #eee;
  transition: transform 0.5s;
}

.carousel-slide {
  flex: 1 0 100%;
  min-height: 100px;
  background: #eee;
}
<div class="carousel">
  <div class="carousel-mover">
    <div class="carousel-slide">
      Page 1 Home
      <button type="button" class="next">NEXT</button>
    </div>
    <div class="carousel-slide">
      Page 2
      <button type="button" class="prev">PREV</button>
      <button type="button" class="next">NEXT</button>
    </div>
    <div class="carousel-slide">
      Page 3 End
      <button type="button" class="prev">PREV</button>
      <button type="button" class="next">GO HOME</button>
    </div>
  </div>
</div>

Example with jQuery and your code

Another not so good example using jQuery with your somewhat rigid naming (since the use of ID) and markup:

$(function(){
  
  var $slide = $("#slides");      // Cache the elements you plan to reuse!
  var $pages = $slide.children(); // Get the actual slides pages
  var slideW = $slide.width();
  var c = 0;                      // Use a counter
  
  // Use classes instead of ID!
  $('.prev, .next').click(function( e ){
    c = $(this).is(".next") ? ++c : --c;             // incr/decr. counter
    $slide.animate({scrollLeft: slideW * c }, 600);  // Anim by multiplying
  });
  
});
#slides{  
  position:relative;
  overflow:hidden;
  margin:0 auto;
  background:#cf5;
  width:100%;
  height:200px;
  white-space:nowrap;
}
#slides div{
  position:relative;
  display:inline-block;
  margin-right:-4px;
  white-space:normal;
  vertical-align:top;
  *display:inline;
  background:#eee;
  width:100%;
  height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slides">
  <div>
    Content 1
    <a href="#" class="next">Show Content 2</a>
  </div>
  
  <div>
  Content 2
    <a href="#" class="prev">Show Content 1</a>
    <br>
    <a href="#" class="next">Show Content 3</a>
  </div>
  
  <div>
  Content 3
    <a href="#" class="prev">Show Content 2</a>
  </div>
</div>

To recap:
instead of animating always to a fixed +- width slideW the above makes use of a variable c that increments / decrements at each prev/next click respectively. Multiplied by the slideshow width you get the scrollLeft position or, if you use CSS, the transform: translateX percentage.

like image 75
Roko C. Buljan Avatar answered Jan 28 '26 05:01

Roko C. Buljan


Actually, in this particular context, you can just increment(or decrement) value for scrollLeft (much simpler solution i would say):

var slideW = $('#slides').width();


  // Next slide
  $('.next-slide').click(function( e ){
    e.preventDefault(); 

    $('#slides').animate({scrollLeft:"+="+slideW}, 600);
  });

  //previous slide
    $('.back-slide').click(function( e ){
    e.preventDefault();
    $('#slides').animate({scrollLeft: "-="+slideW }, 600);
  });

Problem was that your scrollLeft value was always static, this way it is dynamic.

Demo: https://jsfiddle.net/x7p65b1v/1/

And, use class for next/prev buttons, of course.

like image 30
sinisake Avatar answered Jan 28 '26 06:01

sinisake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!