Zbarcea Christian Zbarcea Christian - 1 year ago 94
jQuery Question

jquery slide div within a div

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.

Answer Source

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


  $('.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);


  position: relative;
  overflow: hidden;
.gallery .movable{
  display: flex;
  height: 70vh;
  transition: transform 0.4s;
.gallery .movable > div {
<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>
  <button class="prev">Prev</button>
  <button class="next">Next</button>

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 %

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download