Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal slideshow with DIVs

I have a container div element, this should contain all child div elements. I saw this thread: Slide a div offscreen using jQuery and I was wondering how to implement it (within a div element and not in the body). The code is working fine, but what if the "wrapper" div element has 500px width, how am I supposed to wrap the child divs? Am I need to use iframe or ...?

For a better understanding I made this image: enter image description here

The red rectangle would be a window and the grey background the wall. You can only see trough the window and see the current div element. If you push the right button -aqua- you will see the green div and if you push the left button you will see the yellow div.

Notice: Div elements should move and not the wall.

like image 656
Zbarcea Christian Avatar asked Mar 11 '13 12:03

Zbarcea Christian


1 Answers

jQuery for the logic and CSS3 for transition and transform.
Multiple galleries + Auto-slide + Pause on hover:

$(function(){

  $('.gallery').each(function() {

    var $gal     = $(this),
        $movable = $(".movable", $gal), 
        $slides  = $(">*", $movable),
        N        = $slides.length,
        C        = 0,
        itv      = null;
    
    function play() { itv = setInterval(anim, 3000); }
    function stop() { clearInterval(itv); }
    function anim() {
      C = ($(this).is(".prev") ? --C : ++C) <0 ? N-1 : C%N;
      $movable.css({transform: "translateX(-"+ (C*100) +"%)"});
    }
    
    $(".prev, .next", this).on("click", anim);
    $gal.hover(stop, play);
    play();

  });

});
.gallery{
  position: relative;
  overflow: hidden;
}
.gallery .movable{
  display: flex;
  height: 70vh;
  transition: transform 0.4s;
}
.gallery .movable > div {
  flex:1;
  min-width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Pause on hover and autoslide

<div class="gallery">
  <div class="movable">
    <div style="background:#0af">1 <p style="position:absolute; top:400px;">aaaa</p></div>
    <div style="background:#af9">2</div>
    <div style="background:#f0a">3</div>
  </div>
  <button class="prev">Prev</button>
  <button class="next">Next</button>
</div>

As many galleries as you want

Count the number of slides and put into a counter C.
On prev/next click manipulate C
On autoslide $(this).is(".prev") will also evaluate as false so ++C will be used, just like clicking the Next button.
On mouseenter simply clearInterval the currently running itv and on mouseleave (the second .hover argument) reinitialize the itv

The animation is achieved by multiplying C*100 and translateX by - C * 100 %

like image 98
Roko C. Buljan Avatar answered Oct 05 '22 02:10

Roko C. Buljan