HTML
<div class="carousel" id="carousel"> <div class="carousel-inner"> <img src="img/1.jjpg" alt=" Singkirkan scroll kafe jikalau JavaScript aktif jQuery Carousel"> <img src="img/2.jjpg" alt=" Singkirkan scroll kafe jikalau JavaScript aktif jQuery Carousel"> <img src="img/3.jjpg" alt=" Singkirkan scroll kafe jikalau JavaScript aktif jQuery Carousel"> <img src="img/4.jjpg" alt=" Singkirkan scroll kafe jikalau JavaScript aktif jQuery Carousel"> </div> </div> <nav class="carousel-nav" id="carousel-nav"> <button data-direction="prev">Prev</button> <button data-direction="next">Next</button> </nav>
CSS
.carousel { width:400px; overflow:auto; margin:0 auto .7em; } .carousel, .carousel-inner { height:100px; } .carousel img { width:100px; height:100px; background-color:#ccc; display:block; float:left; margin:0 5px; } .carousel-nav { text-align:center; } .carousel-nav button { cursor:pointer; }
jQuery
(function($) { var $carousel = $('#carousel'), $container = $carousel.find('.carousel-inner'), $nav = $('#carousel-nav'), $img = $container.find('img'), totalWidth = ($img.outerWidth()+parseInt($img.css('margin-left'),10)+parseInt($img.css('margin-right'),10))*$img.length; $carousel.css('overflow', 'hidden'); // Singkirkan scroll kafe jikalau JavaScript aktif $container.css('width', totalWidth); // Set lebar `.carousel-inner` selebar => [jumlah gambar + lebar gambar + margin kiri dan kanan gambar] $nav.find('button').on("click", function() { // Animasikan properti `scrollLeft` ke kiri/ke kanan, // menurut nilai atribut `data-direction` pada tombol yang diklik var dir = $(this).data('direction'); $carousel.stop().animate({ scrollLeft: (dir == "next") ? "+=100px" : "-=100px" }, 200); }); })(jQuery);