Why does my slider go blank after reaching the end? - javascript

I'm having a two issues/problems with the following slide.
It is a "double slider", so, two simultaneous slider in body section.
First is that when i reach the last image (9-nth, cos that much both sliders contain), the second slider continues to work properly (sliding images infinitely) but the first one just get blank.
Or if i click on previous button on begining then second doesn't work and images disapear, while the first one work nicely. Can't figure it out why. I've tried changing the "id" in the HTML and styling it but nothing change.
Second is, that i finally need to make it more dynamic, so, to avoid hardcoding images in the HTML and to putt them in JS and somehow append them in the DOM, but don't know what exactlly to do; creating an array, or using the "createElement"?
And which logic could be usable to actually include them in the DOM and have the following slider(s), considering the provided code?
Since it's my just second slider which i'm making, i found it pretty much hard, so any help/hint/advice is welcomed.
P.S Must be in jQuery and plugins excluded, so please don't provide any plugins links.
Thank you in advance.
var slides = $('.slide');
slides.first().before(slides.last());
$('button').on('click', function() {
// Selecting the slides
slides = $('.slide');
// Selecting button
var button = $(this);
// Register active slide
var activeSlide = $('.active');
// Next function
if (button.attr('id') == 'next') {
slides.last().after(slides.first());
activeSlide.removeClass('active').next('.slide').addClass('active');
}
// Previous function
if (button.attr('id') == 'previous') {
slides.first().before(slides.last());
activeSlide.removeClass('active').prev('.slide').addClass('active');
}
});
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.slider {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.slide {
width: 100%;
height: 300px;
position: absolute;
transition: 0.6s ease;
transform: translate(-100%, 0);
}
.slide img {
width: 100%;
height: 300px;
}
.slide.active {
transform: translate(0, 0);
}
.slide.active~.slide {
transform: translate(100%, 0);
}
body {
text-align: center;
}
button {
margin-top: 20px;
border: none;
border-radius: 0;
background: aqua;
color: #333;
padding: 10px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider">
<div class="slide active">
<img src="Assets/slider-image-1.jpg" alt="">
</div>
<div class="slide">
<img src="Assets/slider-image-2.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-3.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-4.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-5.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-6.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-7.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-8.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-9.jpg">
</div>
</div>
<div class="slider">
<div class="slide active">
<img src="Assets/slider-image-1.jpg" alt="">
</div>
<div class="slide">
<img src="Assets/slider-image-2.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-3.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-4.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-5.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-6.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-7.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-8.jpg">
</div>
<div class="slide">
<img src="Assets/slider-image-9.jpg">
</div>
</div>
<button id="previous"><img src="Assets/arrow-blue-left.png" alt=""></button>
<button id="next"><img src="Assets/arrow-blue-right.png" alt=""></button>

Your code doesn't work properly because the slides = $('.slide') variable contains all slides from both sliders. You have to manipulate the slides in the to sliders independently. The second failure is that in your example the first slide is the initial active slide. Only slides in range second -> penultimate are allowed. Working example here
function handleSlide(slider, direction) {
var slides = $(slider).find('.slide');
if(slides.length < 1) return;
// Register active slide
var activeSlide = $(slider).find('.active');
// Next function
if (direction == 'next') {
slides.last().after(slides.first());
activeSlide.removeClass('active').next('.slide').addClass('active');
}
// Previous function
if (direction == 'previous') {
slides.first().before(slides.last());
activeSlide.removeClass('active').prev('.slide').addClass('active');
}
}
$('button').on('click', function() {
var button = $(this);
handleSlide($("#slider1"), $(button).attr('id'));
handleSlide($("#slider2"), $(button).attr('id'));
});

Loading images dinamically: You can do that by defining an array which contains the images and you can append the images into the slider using the jQuery 'append' method. Working example on jsFiddle.
function fillSliders(slider, images) {
$(slider).empty();
for(var i = 0; i < images.length; i++) {
if(typeof images[i] == "string" && images[i] !== "") {
var active = (i == 1) ? " active" : "";
$(slider).append('<div class="slide'+active+'"><img src="'+images[i]+'"
alt="image-'+i+'" /></div>');
}
}
}
var images = ["image1.jpg", "image2.jpg","image3.jpg","image4.jpg"];
fillSliders($("#slider"), images);

Related

Animated gif alternative using jQuery to animate an image sequence

I put together this very simple jQuery code to animate a sequence of images. It works perfectly. you can view it here.
But now I am trying to update the code so it could work on multiple image sequences at once as long as it has its own class that is referenced in the jQuery code. So I updated it - view below. Unfortunately my updates are not working. Can you guys help me resolve this issue? Thank you in advance!
let aniOne = $(".animation.first img");
let aniTwo = $(".animation.second img");
let currentImg = 0;
function changeImg(allImg){
$(allImg[currentImg]).fadeOut(0, function(){
if(currentImg == allImg.length -1){
currentImg = 0;
}else {
currentImg++;
}
$(allImg[currentImg]).fadeIn(0)});
}
setInterval(changeImg(aniOne), 0050);
setInterval(changeImg(aniTwo), 0050);
.animation {
width: 30%;
}
.animation img {
display: none;
}
.animation img:first-of-type {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animation first">
<img src="http://s23.postimage.org/t57meexkb/horse_1.png">
<img src="http://s23.postimage.org/i86apnasr/horse_2.png">
<img src="http://s23.postimage.org/6kc8v3lnv/horse_3.png">
<img src="http://s23.postimage.org/w4ej1j71n/horse_4.png">
<img src="http://s23.postimage.org/ddclrdch7/horse_5.png">
<img src="http://s23.postimage.org/nbxkdulwr/horse_6.png">
<img src="http://s23.postimage.org/phrv8cpd7/horse_7.png">
<img src="http://s23.postimage.org/n1un88wob/horse_8.png">
<img src="http://s23.postimage.org/9yz0oz6gb/horse_9.png">
<img src="http://s23.postimage.org/6gn0sl5kb/horse_10.png">
<img src="http://s23.postimage.org/vnxwsu8ob/horse_11.png">
<img src="http://s23.postimage.org/bhuetyd0r/horse_12.png">
<img src="http://s23.postimage.org/imc82zka3/horse_13.png">
<img src="http://s23.postimage.org/auvi4fg4r/horse_14.png">
</div>
<div class="animation second">
<img src="https://i.imgur.com/5QGZklx.png">
<img src="https://i.imgur.com/5QGZklx.png">
<img src="https://i.imgur.com/i1oLaES.png">
</div>
As Chris G stated above:
The working code uses setInterval(changeImg, 50) which will work fine. The problem with your current attempt is setInterval(changeImg(aniOne), 50) which evaluates to a call to changeImg(aniOne), then a call to setInterval(undefined, 50) (since changeImg doesn't return anything). If you want this to work, you need to make changeImg into a function that returns a function. – Chris G
After we add these problems, we then have the issue of both animations sharing the currentImg variable, so instead I made two different variables and passed them along with the images. You can handle this many different ways.
let aniOne = $(".animation.first img");
let aniTwo = $(".animation.second img");
let num1 = 0;
let num2 = 0;
function changeImg(allImg, num){
function main(){
$(allImg[num]).fadeOut(0, function(){
if(num == allImg.length -1){
num = 0;
}else {
num++;
}
$(allImg[num]).fadeIn(0)});
}
return main;
}
setInterval(changeImg(aniOne, num1), 0050);
setInterval(changeImg(aniTwo, num2), 0050);
.animation {
width: 30%;
}
.animation img {
display: none;
}
.animation img:first-of-type {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animation first">
<img src="http://s23.postimage.org/t57meexkb/horse_1.png">
<img src="http://s23.postimage.org/i86apnasr/horse_2.png">
<img src="http://s23.postimage.org/6kc8v3lnv/horse_3.png">
<img src="http://s23.postimage.org/w4ej1j71n/horse_4.png">
<img src="http://s23.postimage.org/ddclrdch7/horse_5.png">
<img src="http://s23.postimage.org/nbxkdulwr/horse_6.png">
<img src="http://s23.postimage.org/phrv8cpd7/horse_7.png">
<img src="http://s23.postimage.org/n1un88wob/horse_8.png">
<img src="http://s23.postimage.org/9yz0oz6gb/horse_9.png">
<img src="http://s23.postimage.org/6gn0sl5kb/horse_10.png">
<img src="http://s23.postimage.org/vnxwsu8ob/horse_11.png">
<img src="http://s23.postimage.org/bhuetyd0r/horse_12.png">
<img src="http://s23.postimage.org/imc82zka3/horse_13.png">
<img src="http://s23.postimage.org/auvi4fg4r/horse_14.png">
</div>
<div class="animation second">
<img src="https://i.imgur.com/5QGZklx.png">
<img src="https://i.imgur.com/5QGZklx.png">
<img src="https://i.imgur.com/i1oLaES.png">
</div>

How can I improve this simple image gallery code?

I'm trying to make a basic image gallery with simple html, css and js
This is the code so far.
$('.navigation-1').click(function() {
$('.cat-1').css("opacity", "1");
$('.cat-2').css("opacity", "0");
$('.cat-3').css("opacity", "0");
$('.cat-4').css("opacity", "0");
});
$('.navigation-2').click(function() {
$('.cat-1').css("opacity", "0");
$('.cat-2').css("opacity", "1");
$('.cat-3').css("opacity", "0");
$('.cat-4').css("opacity", "0");
});
$('.navigation-3').click(function() {
$('.cat-3').css("opacity", "1");
$('.cat-1').css("opacity", "0");
$('.cat-2').css("opacity", "0");
$('.cat-4').css("opacity", "0");
});
$('.navigation-4').click(function() {
$('.cat-4').css("opacity", "1");
$('.cat-1').css("opacity", "0");
$('.cat-2').css("opacity", "0");
$('.cat-3').css("opacity", "0");
});
.navigation {
margin-bottom: 15px;
}
.cat {
opacity: 0;
position: absolute;
transition: opacity 0.5s ease-in-out;
}
/* Show a picture at load */
.cat-1 {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="navigation">
<button class="nav navigation-1">Cat 1</button>
<button class="nav navigation-2">Cat 2</button>
<button class="nav navigation-3">Cat 3</button>
<button class="nav navigation-4">Cat 4</button>
</div>
<img class="cat cat-1" src="http://placekitten.com/300/200" alt="">
<img class="cat cat-2" src="http://placekitten.com/300/201" alt="">
<img class="cat cat-3" src="http://placekitten.com/301/200" alt="">
<img class="cat cat-4" src="http://placekitten.com/301/201" alt="">
How do I dynamically generate the buttons and hide the other images, when one image is shown.
I used opacity to show and hide images, but feel free to use whatever suits you best.
I'm sure the this keyword is useful here, but how?
How about the following... where I've added a "data-index" attribute to the "navigation" buttons.
The on button click you hide all "cat" items, and then show the required one by targeting it using the "data-index" attribute.
$('.nav').click(function() {
$('.cat').css("opacity", "0");
var id = $(this).data("index");
$('.cat-' + id).css("opacity", "1");
});
.navigation {
margin-bottom: 15px;
}
.cat {
opacity: 0;
position: absolute;
transition: opacity 0.5s ease-in-out;
}
/* Show a picture at load */
.cat-1 {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="navigation">
<button class="nav" data-index="1">Cat 1</button>
<button class="nav" data-index="2">Cat 2</button>
<button class="nav" data-index="3">Cat 3</button>
<button class="nav" data-index="4">Cat 4</button>
</div>
<img class="cat cat-1" src="http://placekitten.com/300/200" alt="">
<img class="cat cat-2" src="http://placekitten.com/300/201" alt="">
<img class="cat cat-3" src="http://placekitten.com/301/200" alt="">
<img class="cat cat-4" src="http://placekitten.com/301/201" alt="">
// get all cats
const cats = document.querySelectorAll('.cat')
// gets nav container
const nav = document.querySelector('.navigation')
// for each cat
for (let i = 0; i < cats.length; i++) {
// select current cat
const chosenCat = cats[i];
// create button for it
const button = document.createElement("button");
// add some text to button
button.innerHTML = `Cat ${i + 1}`;
// create onclick function that hides all cats and reveals current
button.onclick = () => {
// use Array.prototype.slice.call because you cant iterate the NodeList
Array.prototype.slice.call(cats).forEach(cat => cat.style.opacity = 0);
chosenCat.style.opacity = 1;
};
// add button to nav container
nav.appendChild(button);
}
// reveal initial cat
cats[0].style.opacity = 1;
.cat {
opacity: 0;
position: absolute;
transition: opacity 0.5s ease-in-out;
top: 0;
}
.navigation {
margin-top: 200px;
}
<img class="cat cat-1" src="http://placekitten.com/300/200" alt="">
<img class="cat cat-2" src="http://placekitten.com/300/201" alt="">
<img class="cat cat-3" src="http://placekitten.com/301/200" alt="">
<img class="cat cat-4" src="http://placekitten.com/301/201" alt="">
<div class="navigation">
</div>

Adding navigation buttons below my slider

I created a fade slider with images, text and links. I'd like to add some navigation bullets below it to control the images.
like this :
http://www.parallaxslider.com/preview_images/skins/bullets_skin.jpg
Here is the slider code:
html
<div class="slides">
<div class="slidiv">
<a href="..." ><img src="..." >
<span> text1 </span></a>
</div>
<div class="slidiv">
<a href="..." ><img src="..." >
<span> text2 </span></a>
</div>
<div class="slidiv">
<a href="..." ><img src="..." >
<span> text3 </span></a>
</div>
<div class="slidiv">
<a href="..." ><img src="...">
<span> text4 </span></a>
</div>
</div>
CSS
.slides {
overflow:hidden;
top:0;
position:relative;
width:100%;
height:206px;
z-index:920;
border-bottom:white 6px solid;
}
.slides img {
position:absolute;
left:0;
top:0;
}
.slides span {
position: absolute;
right: 100px;
top: 160px;
color:white !important;
font-size:20px;
}
Javascript
<script type="text/javascript">
$(function() {
$('.slides .slidiv:gt(0)').hide();
setInterval(function () {
$('.slides').children().eq(0).fadeOut(2000)
.next('.slidiv')
.fadeIn(2000)
.end()
.appendTo('.slides');
}, 6000); // 6 seconds
});
</script>
You have to define a unique id for each slide, then build html for circles (make sure you have a way of referencing which circle matches up to which slide). Then you capture the on click event, clear the interval, cycle forward until the slide in the "current" position matches the circle, then create the interval again. And of course every time it cycles forward you need to set a visual cue for the circle associated with the active slide.
(Demo)
HTML
<div class="slider">
<div class="slides">
<div class="slidiv" id="1">
<a href="...">
<img src="http://placehold.it/350x150/3296fa/ffffff">
<span>text1</span>
</a>
</div>
<div class="slidiv" id="2">
<a href="...">
<img src="http://placehold.it/350x150/fa9632/ffffff">
<span>text2</span>
</a>
</div>
<div class="slidiv" id="3">
<a href="...">
<img src="http://placehold.it/350x150/ff3399/ffffff">
<span>text3</span>
</a>
</div>
<div class="slidiv" id="4">
<a href="...">
<img src="http://placehold.it/350x150/33ff99/ffffff">
<span>text4</span>
</a>
</div>
</div>
<div class="circles">
</div>
</div>
CSS
.circles, .circle {
display: inline-block;
}
.circles {
position: relative;
left: 50%;
transform: translateX(-50%);
}
.circle {
padding: 5px;
border-radius: 100%;
border: 1px solid #444;
}
.active {
background: rgb(50, 150, 250);
}
JAVASCRIPT
$(function () {
$('.slides .slidiv:gt(0)').hide();
$.fn.setActive = function () {
if ($(this).hasClass("slider")) {
$(".active", $(this)).removeClass("active");
$("#circle-" + $(".slidiv:first-child", $(this),$(this)).attr("id"),$(this)).addClass("active");
return this;
}
return false;
}
$.fn.cycleFwd = function(rateStart,rateEnd) {
if ($(this).hasClass("slider")) {
$('.slides', $(this)).children()
.eq(0)
.fadeOut(rateStart)
.next('.slidiv')
.fadeIn(rateEnd)
.end()
.appendTo($('.slides', $(this)));
$(this).setActive($('.slidiv:first-child',$(this)).attr("id"));
return this;
}
return false;
}
$.fn.cycleFwdTo = function (id,rate) {
if($(this).hasClass("slider")) {
var current = $(".slidiv:first-child", $(this));
if(current.attr("id") === id) return true;
var count = id;
if(current.attr("id") > id) {
count = Number(current.nextAll().length) + Number(id) + 1;
}
if(count - current.attr("id") === 1) {
$(this).cycleFwd(rate,2000);
} else {
$(this).cycleFwd(rate,0);
$(this).cycleFwdTo(id,0);
}
return this;
}
return false;
}
$(".circle").on("click", function () {
clearInterval(window.interval);
var newFirst = $(this).attr("data-moveto");
$(this).parent().parent().cycleFwdTo(newFirst,2000);
var self = this;
window.interval = setInterval(function () {
$(self).parent().parent().cycleFwd(2000,2000);
}, 6000); // 6 seconds
});
$('.slider').each(function(){
var self = this;
window.interval = setInterval(function () {
$(self).cycleFwd(2000,2000);
}, 6000); // 6 seconds
});
});
EDIT:
This answer is not very good because it does not very well explain how it works, but this falls into "I could write a novel" explaining all of the different methods of doing what the OP has asked and how each method works. If someone else wanted to come along and offer better explanations of how this code works, I would approve.

simple jquery slideshow with navigation?

So I'm in the process of creating a pretty simple jQuery/CSS slideshow for a course of mine. It's about ten pages long, and right now it works fine if you want to just go from beginning to end in that order, but if you need to refresh the page for any reason, it sends you back to the first page. Since it's on the longer end, I'd like to be able to "click" to a certain page... is this possible without getting too complicated?
Here's my jQuery
function checkNav() {
if ($('.active-slide').hasClass('first')) {
$('.prev').hide();
$('.next').show();
} else if ($('.active-slide').hasClass('last')) {
$('.next').hide();
$('.prev').show();
} else {
$('.next').show();
$('.prev').show();
}
}
var main = function() {
checkNav();
$('.next').click(function() {
var currentSlide = $('.active-slide');
var nextSlide = currentSlide.next('.slide');
var currentDot = $('.active-dot');
var nextDot = currentDot.next();
//if nextslide is last slide, go back to the first
if (nextSlide.length === 0) {
nextSlide = $('.slide').first();
nextDot = $('.dot').first();
}
currentSlide.fadeOut(500).removeClass('active-slide');
nextSlide.fadeIn(1100).addClass('active-slide');
currentDot.removeClass('active-dot');
nextDot.addClass('active-dot');
checkNav();
});
//prev slide function
$('.prev').click(function() {
var currentSlide = $('.active-slide');
var prevSlide = currentSlide.prev('.slide');
var currentDot = $('.active-dot');
var prevDot = currentDot.prev();
//if prevslide is last slide, go back to the first
if (prevSlide.length === 0) {
prevSlide = $('.slide').last();
prevDot = $('.dot').last();
}
currentSlide.fadeOut(600).removeClass('active-slide');
prevSlide.fadeIn(600).addClass('active-slide');
currentDot.removeClass('active-dot');
prevDot.addClass('active-dot');
checkNav();
});
};
$(document).ready(main);
And here's a rough markup of what the HTML looks like
<div class="slide active-slide first">
<div class="content">
<p>First Slide</p>
</div>
</div>
<div class="slide">
<div class="content">
<p>second slide</p>
</div>
</div>
<div class="slide last">
<div class="content">
<p>third slide</p>
</div>
</div>
<div class="slider-nav">
<div class="prev">prev</div>
<ul class="dots">
<li class="dot active-dot">•</li>
<li class="dot">•</li>
<li class="dot">•</li>
</ul>
<div class="next">next</div>
</div>
Here's the jsFiddle ... I'd like to be able to click on one of the bullets and go to that corresponding slide....
$('ul.dots li').click(function(){
var num = $(this).index();
var currentSlide = $('.active-slide');
var nextSlide = $('.slide:eq('+num+')');
var currentDot = $('.active-dot');
var nextDot = $(this);
currentSlide.fadeOut(600).removeClass('active-slide');
nextSlide.fadeIn(600).addClass('active-slide');
currentDot.removeClass('active-dot');
nextDot.addClass('active-dot');
checkNav();
});
Add IDs to the divs. For instance:
<div class="slide active-slide first" id="1">
<div class="content">
<p>First Slide</p>
</div>
</div>
<div class="slide" id="2">
<div class="content" >
<p>second slide</p>
</div>
</div>
<div class="slide last" id="3">
<div class="content">
<p>third slide</p>
</div>
</div>
Then you can target specific slides using something like:
<ul class="dots">
<li class="dot active-dot"><a onclick="goto(1)">•</a></li>
<li class="dot"><a onclick="goto(2)">•</a></li>
<li class="dot"><a onclick="goto(3)">•</a></li>
</ul>
<script>
function goto(slide){
$(".slide").removeClass("active-slide");
$("#"+slide).addClass("active-slide");
$("#"+slide).show();
}
We need a way to "index" these items, I will do it by child so add a parent div class called slider:
<div id="slider">
...slides here...
</div>
You need to use localStorage (used to save data between pages) to keep track of both what slide you are on and what dot you are on in the nav bar. This can save data even when we leave the page (when it refreshes), making it so we still know our last page we where on. I will use this to keep track of the current index of each slide. So when the page loads we need to check that if our localStorage item exist:
// If we have saved data add it's index to active-slide
if(localStorage.getItem("activeSlide")) {
$("#slider div.slide")
.eq(localStorage.getItem("activeSlide"))
.addClass("active-slide");
$('.dots li.dot')
.eq(localStorage.getItem("activeSlide"))
.addClass("active-dot");
} else { // Otherwise make them both 0
$("#slider div.slide")
.eq('0')
.addClass("active-slide");
$('.dots li.dot')
.eq('0')
.addClass("active-dot");
}
Then when we move to the next slide next or the last slide prev we update the localStorage item to the current index of the item in active-slide:
// Make the current index of the item in active slide our updated variable
localStorage.setItem( "activeSlide",
$("#slider div.slide").index($(".active-slide")) );
Here is a working example
This way when the page refreshes we stay on the last slide we where looking at before.
<!doctype html>
<html>
<head>
<style>
body{
text-align: center;
}
#slideshow{
margin:0 auto;
width:600px;
height:450px;
overflow: hidden;
position: relative;
}
#slideshow ul{
list-style: none;
margin:0;
padding:0;
position: absolute;
}
#slideshow li{
float:left;
}
#slideshow a:hover{
background: rgba(0,0,0,0.8);
border-color: #000;
}
#slideshow a:active{
background: #990;
}
.slideshow-prev, .slideshow-next{
position: absolute;
top:180px;
font-size: 30px;
text-decoration: none;
color:#fff;
background: rgba(0,0,0,0.5);
padding: 5px;
z-index:2;
}
.slideshow-prev{
left:0px;
border-left: 3px solid #fff;
}
.slideshow-next{
right:0px;
border-right: 3px solid #fff;
}
</style>
</head>
<body>
<div id="slideshow">
«
<ul>
<li><img src="1.jpg" alt="photo1" /></li>
<li><img src="2.jpg" alt="photo2" /></li>
<li><img src="3.jpg" alt="photo3" /></li>
<li><img src="4.jpg" alt="photo4" /></li>
</ul>
»
</div>
<!--
We use Google's CDN to serve the jQuery js libs.
To speed up the page load we put these scripts at the bottom of the page
-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
//an image width in pixels
var imageWidth = 600;
//DOM and all content is loaded
$(window).ready(function() {
var currentImage = 0;
//set image count
var allImages = $('#slideshow li img').length;
//setup slideshow frame width
$('#slideshow ul').width(allImages*imageWidth);
//attach click event to slideshow buttons
$('.slideshow-next').click(function(){
//increase image counter
currentImage++;
//if we are at the end let set it to 0
if(currentImage>=allImages) currentImage = 0;
//calcualte and set position
setFramePosition(currentImage);
});
$('.slideshow-prev').click(function(){
//decrease image counter
currentImage--;
//if we are at the end let set it to 0
if(currentImage<0) currentImage = allImages-1;
//calcualte and set position
setFramePosition(currentImage);
});
});
//calculate the slideshow frame position and animate it to the new position
function setFramePosition(pos){
//calculate position
var px = imageWidth*pos*-1;
//set ul left position
$('#slideshow ul').animate({
left: px
}, 300);
}
</script>
</body>
</html>

How the get scroll the div horizontal using left and right buttons

I have a class called portfolio-items where it will scroll horizontal. I need jQuery which helps me to scroll to the next and previous closest classes using my next and previous buttons. Need it more specific like on click my buttons it need the get the position of my closest div and scroll accordingly left or right.
Below Is my code
MARKUP
<span class='arrow-left'>left</span>
<span class='arrow-right'>right</span>
<div class='row offer-pg-cont'>
<div class='offer-pg'>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
<div class="col-md-3 portfolio-item">
<img src="images/a1.png" class="items" height="100" alt="" />
</div>
</div>
</div>
CSS
.offer-pg-cont{
width: 100%;
overflow-x: auto;
margin: 0px;
}
span.arrow-left,span.arrow-right{
display: block;
position: absolute;
background-color: #555;
top: 40px;
color:white;
z-index: 2;
cursor: pointer;
}
span.arrow-left{
left: 0px;
}
span.arrow-right{
right: 0px;
}
span.arrow-left:hover,.offer-pg span.arrow-right:hover{
background-color: #333;
}
.offer-pg{
width: 1500px;
}
.item-wrapper.offer-con{
background-color: #333 !important;
}
.offer-con .left-item h4 {
color: #fff;
font-weight: normal;
margin: 0px;
}
.offer-con .right-item{
float: right;
padding: 10px;
}
.offer-con .right-item h5{
color: #cb9944;
margin: 0px;
font-size: 14px;
}
.offer-pg > .portfolio-item{
width: 100px;
background-color:blue;
margin-left:10px;
float:left;
}
Please check my fiddle DEMO
Thanks.
try
$(document).ready(function(){
$(".arrow-left").click(function(){
$(".offer-pg-cont").animate({scrollLeft: "-="+100});
});
$(".arrow-right").click(function(){
$(".offer-pg-cont").animate({scrollLeft: "+="+100});
});
});
demo http://jsfiddle.net/xQh5J/177/
exactly you can detect width one item by :
var widthOneItem = parseInt($(".col-md-3").first().css("width"))+parseInt($(".col-md-3").first().css("margin-left"))+parseInt($(".col-md-3").first().css("margin-right"))+parseInt($(".col-md-3").first().css("padding-left"))+parseInt($(".col-md-3").first().css("padding-right"));
And edit code
$(document).ready(function(){
var widthOneItem = parseInt($(".col-md-3").first().css("width"))+parseInt($(".col-md-3").first().css("margin-left"))+parseInt($(".col-md-3").first().css("margin-right"))+parseInt($(".col-md-3").first().css("padding-left"))+parseInt($(".col-md-3").first().css("padding-right"));
$(".arrow-left").click(function(){
$(".offer-pg-cont").animate({scrollLeft: "-="+widthOneItem});
});
$(".arrow-right").click(function(){
$(".offer-pg-cont").animate({scrollLeft: "+="+widthOneItem});
});
});
demo http://jsfiddle.net/xQh5J/180/
I wrote a few lines and forked your fiddle: http://jsfiddle.net/jbrosi/c6kf2/ (I also accidentally updated yours - sorry for that).
This solution won't break if you manually scroll via mousewheel or keyboard in the container and it should respect items with varying sizes, too (just make sure your container is big enough for them to stay in one line).
$(document).ready(function() {
//cache our items and containers
var items = $(".portfolio-item");
var scrollContainer = $(".offer-pg-cont");
/**
* Fetches the next or previous item from items
*
* #param conntainer {JQueryElement} scroll-container in which the items can be found
* #param items {Array} items to be searched through
* #param isNext {boolean} set to true (default) if you want the next item, to false if you want the previous one
* #returns {*}
*/
function fetchItem(container, items, isNext) {
var i,
scrollLeft = container.scrollLeft();
//set isNext default to true if not set
if (isNext === undefined) {
isNext = true;
}
if (isNext && container[0].scrollWidth - container.scrollLeft() <= container.outerWidth()) {
//we reached the last one so return the first one for looping:
return $(items[0]);
}
//loop through items
for (i = 0; i < items.length; i++) {
if (isNext && $(items[i]).position().left > 0) {
//this item is our next item as it's the first one with non-negative "left" position
return $(items[i]);
} else if (!isNext && $(items[i]).position().left >= 0) {
//this is our previous item as it's the one with the smallest negative "left" position
//if we're at item 0 just return the last item instead for looping
return i == 0 ? $(items[items.length - 1]) : $(items[i-1]);
}
}
//nothing found
return null;
}
/**
* Moves the scrollcontainer to the next/previous item (depending on event.data.direction).
*
* #param event
*/
function moveToItem(event) {
//fetch the next/previous item:
var isNext = event.data.direction == "next";
var item = isNext ? fetchItem(scrollContainer, items, true) : fetchItem(scrollContainer, items, false);
if (item) {
//scroll to item
scrollContainer.animate({"scrollLeft": item.position().left + scrollContainer.scrollLeft()}, 400);
}
}
//bind events
$(".arrow-left").click({direction: "prev"}, moveToItem);
$(".arrow-right").click({direction: "next"}, moveToItem);
});
Update: Edited the code so it loops when reaching first / last item
If this is thumbnail scroller you can use this plugin or this
You can customize it also, hope that will help you :)
You can try below code:
Demo
$(".arrow-left").click(function(){
$(".offer-pg-cont").animate({scrollLeft: "-="+110});
});
$(".arrow-right").click(function(){
$(".offer-pg-cont").animate({scrollLeft: "+="+110});
});

Categories

Resources