Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very Simple jQuery Div Slider

Tags:

html

jquery

css

I would like to put 5 divs on my page but width of the page doesn`t let me do it. So I thought I can show only 3 of them and people who wants to see other ones can click right-left arrows to see. I want it to work that way very simple. Anybody has an idea of the best way to do it ?

like image 207
Extelliqent Avatar asked Dec 27 '22 08:12

Extelliqent


2 Answers

Here is how to do so, by using jQuery.DIYslider, a lightweight and customizable jQuery slider.

Demonstration of the following code: http://jsfiddle.net/bj4yZ/155/

You'll notice this plugin makes it extremely easy to do whatever you want to do.

You'll find all of this plugin's options, methods and events on the page linked above.

HTML

<button id="go-left">&laquo;</button> <button id="go-right">&raquo;</button>

<div class="slider"><!-- The slider -->
    <div><!-- A mandatory div used by the slider -->
        <!-- Each div below is considered a slide -->
        <div class="a">Div #1</div>
        <div class="b">Div #2</div>
        <div class="c">Div #3</div>
        <div class="d">Div #4</div>
        <div class="e">Div #5</div>
    </div>
</div>

JavaScript

$(".slider").diyslider({
    width: "400px", // width of the slider
    height: "200px", // height of the slider
    display: 3, // number of slides you want it to display at once
    loop: false // disable looping on slides
}); // this is all you need!

// use buttons to change slide
$("#go-left").bind("click", function(){
    // Go to the previous slide
    $(".slider").diyslider("move", "back");
});
$("#go-right").bind("click", function(){
    // Go to the previous slide
    $(".slider").diyslider("move", "forth");
});
like image 72
user1728278 Avatar answered Dec 29 '22 21:12

user1728278


wouldn't be hard for you to code at all, so theory goes like this

html structure

.outter-container
  .inner container
    .slide slide1
    .slide slide2
    .slide slide3
    .slide slide4
    .slide slideX
  1. get window width, slide width
  2. window width / 3 = slide width ( to make it easier, always 3 slides at once)
  3. index each slides, than apply index * slide width ( this equal to horizontal position )
  4. set the outter container to position relative, width=window width, overflow=hidden, and inner container to position absolute, left:0, top:0 and slides to position:absolute
  5. set the each slides css left: index*width (point 3)
  6. there you go, successfully hide the other slides, time to interaction
  7. next.click -> slide animate inner container left: -= slide.width (opposite for left.click)
  8. and show/hide left/right button if inner-container is left = 0 else.... to disable people clicking when no more slides are hidden
like image 24
devric Avatar answered Dec 29 '22 22:12

devric