How to add next previous button to js jQuery slider? - javascript

I have watch a tutorial on youtube on how to create slider using jquery jquery tutorial slider
But no Previous and Next Button
How to add Previous and Next Button to Jquery Slider
Here is the code:
'use strict';
$(function() {
//settings for slider
var width = 720;
var animationSpeed = 1000;
var pause = 3000;
var currentSlide = 1;
//cache DOM elements
var $slider = $('#slider');
var $slideContainer = $('.slides', $slider);
var $slides = $('.slide', $slider);
var interval;
function startSlider() {
interval = setInterval(function() {
$slideContainer.animate({'margin-left': '-='+width}, animationSpeed, function() {
if (++currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
}, pause);
}
function pauseSlider() {
clearInterval(interval);
}
$slideContainer
.on('mouseenter', pauseSlider)
.on('mouseleave', startSlider);
startSlider();
});
#slider {
width: 720px;
height: 400px;
overflow: hidden;
}
#slider .slides {
display: block;
width: 6000px;
height: 400px;
margin: 0;
padding: 0;
}
#slider .slide {
float: left;
list-style-type: none;
width: 720px;
height: 400px;
}
/* helper css, since we don't have images */
.slide1 {background: red;}
.slide2 {background: blue;}
.slide3 {background: green;}
.slide4 {background: purple;}
.slide5 {background: pink;}
<div class="container">
<div class="header">
<h1 class="text-muted">jQuery Basic Slider</h1>
</div>
<div id="slider">
<ul class="slides">
<li class="slide slide1">slide1</li>
<li class="slide slide2">slide2</li>
<li class="slide slide3">slide3</li>
<li class="slide slide4">slide4</li>
<li class="slide slide5">slide5</li>
<li class="slide slide1">slide1</li>
</ul>
</div>
</div>
Thank you
Thank you

Try this! I added comments in the code about why I did what I did.
$(function() {
//settings for slider
var width = 720;
var animationSpeed = 1000;
var pause = 3000;
var currentSlide = 1;
var margin = 0; //Create variable for margin
//cache DOM elements
var $slider = $('#slider');
var $slideContainer = $('.slides', $slider);
var $slides = $('.slide', $slider);
var length = $slides.length;
var interval;
//Make this a function do that you don't need to keep repeating it
function Slider() {
$slideContainer.animate({
'margin-left': margin //make the margin a variable, so that you can access it in multiple functions
}, animationSpeed, function() {
console.log(currentSlide)
if (currentSlide === length) { //Stop incremening currentSlide here so that it'll be easier to increment later
currentSlide = 1;
margin = 0;
$slideContainer.css('margin-left', 0);
}
});
}
function contSlider() { //changed from startSlider to contSlider
interval = setInterval(function() {
margin -= width; //minus width from the margin
currentSlide++; //Stop incremening currentSlide here
Slider() //tell broswer "insert slider code here"
}, pause);
}
function pauseSlider() {
clearInterval(interval);
}
function three() {
clearInterval(interval); //Stop the orignal slider
Slider(); //Immediately perform the slider function
contSlider(); //Continue the slider function
}
function prevSlider() {
if (currentSlide > 1) { //Don't run code if first slide
currentSlide--; //Minus 1 from currentSlide
} else { //if the first slide, move it to the last one
margin = -width * (length - 1); //margin is the value of the last slide
$slideContainer.css('margin-left', margin); //move to the last slide instantly
currentSlide = (length - 1) //make current slide the second last slide (slide 5)
}
margin += width; //Plus a width (to make it move to the previous slide
three(); //Run the three functions
}
function nextSlider() {
if (currentSlide < length){ //Don't run code if last slide
margin -= width; //Minus a width (to make it move to the previous slide
currentSlide++; //Plus 1 from currentSlide
}
three(); //Run the three functions
}
$slideContainer
.on('mouseenter', pauseSlider)
.on('mouseleave', contSlider);
//Make the functions happen when their buttons are clicked (This could be anything)
$(".prev-slide").on("click", prevSlider);
$(".next-slide").on("click", nextSlider) //
contSlider();
});
.button { display: none }
#slider:hover .button {
display: block;
font-size: 3em;
font-weight: bold;
color: #fff;
position: absolute;
top: 180px;
cursor: pointer;
}
.prev-slide {
left: 10px;
}
.next-slide {
right: 10px;
}
#slider {
width: 720px;
height: 400px;
overflow: hidden;
position: relative;
}
#slider .slides {
display: block;
width: 6000px;
height: 400px;
margin: 0;
padding: 0;
}
#slider .slide {
float: left;
list-style-type: none;
width: 720px;
height: 400px;
}
/* helper css, since we don't have images */
.slide1 {
background: red;
}
.slide2 {
background: blue;
}
.slide3 {
background: green;
}
.slide4 {
background: purple;
}
.slide5 {
background: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="header">
<h1 class="text-muted">jQuery Basic Slider</h1>
</div>
<div id="slider">
<div class="prev-slide button"><</div>
<div class="next-slide button">></div>
<ul class="slides">
<li class="slide slide1">slide1</li>
<li class="slide slide2">slide2</li>
<li class="slide slide3">slide3</li>
<li class="slide slide4">slide4</li>
<li class="slide slide5">slide5</li>
<li class="slide slide1">slide1</li>
</ul>
</div>
</div>

you can add a click function to next and prev and adding(next) or deducting(prev) margin-left like this:
$('#next').click(function(){
pauseSlider();
$slideContainer.animate({'margin-left': '-='+width}, animationSpeed, function() {
console.log(width);
if (++currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
startSlider();
});
$('#prev').click(function(){
console.log(currentSlide);
console.log($slides.length);
pauseSlider();
$slideContainer.animate({'margin-left': '+='+width}, animationSpeed, function() {
if (--currentSlide === 1) {
currentSlide = 6;
$slideContainer.css('margin-left', -(width * 5));
console.log('first');
}
});
startSlider();
});
Check the codepen I created for testing: http://codepen.io/adrianrios/pen/evLOyQ
I hope this will help.

Related

How can I fix my slideshow transition error?

I made images and a video slideshow. 3 images and at the end 1 video. It is fine when I made it on a full-screen web page.
But when I made it to half of the screen the transition error showed up, the next image flashed at the bottom of the earlier image.
How can I fix my slideshow transition error?
Can anyone help me?
// Some variables
var timer;
var sWidth = '100%',
sHeight = '80%',
border = 10;
var slideshowSet = false;
var video;
var videoSet = false;
var slidePause = false;
var $el;
var $currentEl = $('.slideshow').find('li').eq(0);
// On document ready
$(function() {
// Set slideshow dimensions + border
setSlideDimensions(sWidth, sHeight, border);
// Show pause button
$('.slideshow').hover(
function() {
if (slideshowSet) {
$('.pause').stop().fadeIn(200);
}
},
function() {
if (slideshowSet) {
$('.pause').fadeOut(200);
}
}
);
// Pause button
$('.pause').click(function() {
if ($(this).text() == '| |') {
// Pause slideshow
slidePause = true;
$(this).text('►');
clearTimeout(timer);
if ($currentEl.find('video').size() == 1) {
video.pause();
}
} else {
// Play slideshow
$(this).text('| |');
if ($currentEl.find('video').size() == 1) {
video.play();
} else {
timer = setTimeout(slide, 2000);
}
}
});
});
// Window ready (all images loaded, but not videos!!)
$(window).ready(function() {
// Hide loader GIF
$('.loader').fadeOut(200);
// Show slideshow
$('.slideshow ul').fadeIn(200);
// Start slideshow
$el = $('.slideshow').find('li');
timer = setTimeout(slide, 2000);
slideshowSet = true;
});
// Function to slide
function slide() {
videoSet = false;
$el = $('.slideshow').find('li');
$el.eq(1).add($el.eq(0)).animate({
'left': '-=' + sWidth
}, {
queue: false,
duration: 300,
complete: function() {
$el.eq(0).animate({
'left': '100%'
}, 0);
$currentEl = $el.eq(1);
if ($(this).index() == 1) {
$('.slideshow ul').append($el.eq(0));
// We chek if it's a video
if ($(this).find('video').size() == 1) {
//If yes we set the variable
video = $(this).find('video')[0];
videoSets();
// If video can play
if (video.canPlayType) {
// Play video
video.play();
} else {
// Error message
alert('No html5');
}
} else {
// If not a video we set timeout to next slide
timer = setTimeout(slide, 2000);
}
}
}
});
}
// Function to set all video events
function videoSets() {
if (!videoSet) {
videoSet = true;
// Video ended
video.addEventListener("ended", function() {
timer = setTimeout(slide, 2000);
});
// Video Playing
video.addEventListener("playing", function() {
clearTimeout(timer);
if (slidePause) {
$('.pause').text('| |');
video.play();
slidePause = false;
}
});
}
}
// Function to set slideshow dimensions
function setSlideDimensions(w, h, b) {
$('.slideshow').css({
width: w,
'height': h,
'padding': b
});
$('.slideshow ul li img, .slideshow ul li video').css({
width: w,
'height': h
});
}
.slideshow {
position: relative;
margin: auto;
}
.slideshow ul {
width: 100%;
height: 100%;
position: relative;
list-style: none;
overflow: hidden;
display: none;
}
.slideshow ul li {
position: relative;
left: 100%;
}
.slideshow ul li:first-child {
left: 0%;
}
video {
background: #434343;
}
.loader {
width: 50px;
height: 50px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
}
.pause {
display: none;
width: 50px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -25px;
margin-top: -25px;
border-radius: 50%;
background: rgba(0,0,0,.6);
z-index: 100;
line-height: 50px;
text-align: center;
font-size: 1.0em;
font-weight: bold;
color: white;
cursor: pointer;
}
.column {
float: left;
width: 50%;
padding: 5px;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div class="row">
<div class="column">
<section class="slideshow">
<div class="pause">| |</div>
<img src="https://c.tenor.com/5o2p0tH5LFQAAAAi/hug.gif" width="50" class="loader" />
<ul>
<li><img src="https://natureconservancy-h.assetsadobe.com/is/image/content/dam/tnc/nature/en/photos/Zugpsitze_mountain.jpg?crop=0%2C176%2C3008%2C1654&wid=2000&hei=1100&scl=1.504" /></li>
<li><img src="https://mymodernmet.com/wp/wp-content/uploads/2021/04/Nature-Sounds-For-Well-Being-03.jpg" /></li>
<li><img src="https://img.freepik.com/free-photo/sunrise-jungle_1385-1689.jpg?w=1380&t=st=1664437209~exp=1664437809~hmac=2f34f36a7ab7d602cc4927fce5ad3063c5d945a169145d997b27e9f78f76f5ad" /></li>
<li><img src="https://img.freepik.com/free-photo/madakaripura-waterfall-is-tallest-waterfall-java_335224-388.jpg?w=1380&t=st=1664437263~exp=1664437863~hmac=5dfd42c39de69c5eebc5a8976d6ffc1ca733db1720a2b984a2d19b0cf5166c50" /></li>
<li><img src="https://img.freepik.com/premium-photo/natural-portraits-rice-fields-mountains-indonesian-rural-areas-with-sunrise-green-morning-dew-asia_80375-80.jpg?w=1380" /></li>
<li>
<video controls id="video1" preload>
<source src="http://media.w3.org/2010/05/sintel/trailer.mp4" type="video/mp4">
</video>
</li>
</ul>
</section>
</div>
<div class="column">
</div> </div>
</body>
</html>

Image slider - slide animation - jQuery

Ok, i'm stuck.
I need to implement animation on my slider over the jQuery. So far i done arrows (navigation) functionality but, can't figure it out how to add sliding effect (1, 2 seconds) after clicking the "next" and "prev" buttons.
Anyone have idea?
$(document).ready(function() {
$('.next').on('click', function() {
var currentImg = $('.current');
var nextImg = currentImg.next();
if(nextImg.length == 0) {
nextImg = $('.slider-secondary img').first();
}
currentImg.removeClass('current');
nextImg.addClass('current');
});
$('.previous').on('click', function() {
var currentImg = $('.current');
var prevImg = currentImg.prev();
if(prevImg.length == 0) {
prevImg = $('.slider-secondary img').last();
}
currentImg.removeClass('current');
prevImg.addClass('current');
});
});
<div class="container">
<div class="slider-primary">
<img src="Assets/arrow-blue-left.png" class="previous" alt="Prev">
<div class="slider-secondary">
<img src="Assets/slider-image-1.jpg" class="current">
<img src="Assets/slider-image-2.jpg">
<img src="Assets/slider-image-3.jpg">
<img src="Assets/slider-image-4.jpg">
<img src="Assets/slider-image-5.jpg">
<img src="Assets/slider-image-6.jpg">
<img src="Assets/slider-image-7.jpg">
<img src="Assets/slider-image-8.jpg">
<img src="Assets/slider-image-9.jpg">
</div>
<img src="Assets/arrow-blue-right.png" class="next" alt="Next">
</div>
</div>
Thanks a lot guys for your help and references. I appreciate it.
Slider must not be automatic, it can work only on arrows(navigation) click, which are (and must be) images/icons.
Also it's not alowed to use any existing scripts, plugins, etc.. so i tried to implement some further logic having in mind and considering all of the conditions above.
It's actually one part of the code test. And must be in jQuery in which i don't flow so well obviously.
Here is the css part also
*{
margin: 0;
padding: 0;
}
.container, .slider-primary{
width:100%;
margin:auto;
overflow: hidden;
position: relative;
}
.slider-secondary{
width:100%;
height:600px;
position:relative;
overflow:hidden;
float:left;
}
.slider-secondary img{
display:none;
width:100%;
height:100%;
}
.slider-secondary img.current{
display:inline-block;
}
.previous, .next{
float:left;
cursor: pointer;
position: absolute;
top: 45%;
width: 30px;
height: 40px;
}
.previous{
margin-left:35px;
z-index:100;
}
.next{
margin-left:-65px;
z-index:100;
}
You can use jQuery animate() Method. Here is the link to the documentation.
But I would suggest using any jQuery lightweight library for the same.
You can go for Responsive and Flexible Mobile Touch Slider - Swiper
Demo of the same!
Here is one working example. Hope it'll help you. for the full reference visit codepen
$('.slider').each(function() {
var $this = $(this);
var $group = $this.find('.slide_group');
var $slides = $this.find('.slide');
var bulletArray = [];
var currentIndex = 0;
var timeout;
function move(newIndex) {
var animateLeft, slideLeft;
advance();
if ($group.is(':animated') || currentIndex === newIndex) {
return;
}
bulletArray[currentIndex].removeClass('active');
bulletArray[newIndex].addClass('active');
if (newIndex > currentIndex) {
slideLeft = '100%';
animateLeft = '-100%';
} else {
slideLeft = '-100%';
animateLeft = '100%';
}
$slides.eq(newIndex).css({
display: 'block',
left: slideLeft
});
$group.animate({
left: animateLeft
}, function() {
$slides.eq(currentIndex).css({
display: 'none'
});
$slides.eq(newIndex).css({
left: 0
});
$group.css({
left: 0
});
currentIndex = newIndex;
});
}
function advance() {
clearTimeout(timeout);
timeout = setTimeout(function() {
if (currentIndex < ($slides.length - 1)) {
move(currentIndex + 1);
} else {
move(0);
}
}, 4000);
}
$('.next_btn').on('click', function() {
if (currentIndex < ($slides.length - 1)) {
move(currentIndex + 1);
} else {
move(0);
}
});
$('.previous_btn').on('click', function() {
if (currentIndex !== 0) {
move(currentIndex - 1);
} else {
move(3);
}
});
$.each($slides, function(index) {
var $button = $('<a class="slide_btn">•</a>');
if (index === currentIndex) {
$button.addClass('active');
}
$button.on('click', function() {
move(index);
}).appendTo('.slide_buttons');
bulletArray.push($button);
});
advance();
});
Try below way.
I have created a demo for you.
Please Find below code:
Html:
<h1>Incredibly Basic Slider</h1>
<div id="slider">
>
<
<ul>
<li>SLIDE 1</li>
<li style="background: #aaa;">SLIDE 2</li>
<li>SLIDE 3</li>
<li style="background: #aaa;">SLIDE 4</li>
</ul>
</div>
<div class="slider_option">
<input type="checkbox" id="checkbox">
<label for="checkbox">Autoplay Slider</label>
</div>
Css:
#import url(https://fonts.googleapis.com/css?family=Open+Sans:400,300,600);
html {
border-top: 5px solid #fff;
background: #58DDAF;
color: #2a2a2a;
}
html, body {
margin: 0;
padding: 0;
font-family: 'Open Sans';
}
h1 {
color: #fff;
text-align: center;
font-weight: 300;
}
#slider {
position: relative;
overflow: hidden;
margin: 20px auto 0 auto;
border-radius: 4px;
}
#slider ul {
position: relative;
margin: 0;
padding: 0;
height: 200px;
list-style: none;
}
#slider ul li {
position: relative;
display: block;
float: left;
margin: 0;
padding: 0;
width: 500px;
height: 300px;
background: #ccc;
text-align: center;
line-height: 300px;
}
a.control_prev, a.control_next {
position: absolute;
top: 40%;
z-index: 999;
display: block;
padding: 4% 3%;
width: auto;
height: auto;
background: #2a2a2a;
color: #fff;
text-decoration: none;
font-weight: 600;
font-size: 18px;
opacity: 0.8;
cursor: pointer;
}
a.control_prev:hover, a.control_next:hover {
opacity: 1;
-webkit-transition: all 0.2s ease;
}
a.control_prev {
border-radius: 0 2px 2px 0;
}
a.control_next {
right: 0;
border-radius: 2px 0 0 2px;
}
.slider_option {
position: relative;
margin: 10px auto;
width: 160px;
font-size: 18px;
}
Js:
jQuery(document).ready(function ($) {
$('#checkbox').change(function(){
setInterval(function () {
moveRight();
}, 3000);
});
var slideCount = $('#slider ul li').length;
var slideWidth = $('#slider ul li').width();
var slideHeight = $('#slider ul li').height();
var sliderUlWidth = slideCount * slideWidth;
$('#slider').css({ width: slideWidth, height: slideHeight });
$('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });
$('#slider ul li:last-child').prependTo('#slider ul');
function moveLeft() {
$('#slider ul').animate({
left: + slideWidth
}, 200, function () {
$('#slider ul li:last-child').prependTo('#slider ul');
$('#slider ul').css('left', '');
});
};
function moveRight() {
$('#slider ul').animate({
left: - slideWidth
}, 200, function () {
$('#slider ul li:first-child').appendTo('#slider ul');
$('#slider ul').css('left', '');
});
};
$('a.control_prev').click(function () {
moveLeft();
});
$('a.control_next').click(function () {
moveRight();
});
});
I hope this will help you.
Let me know if you have any query.
Thank you.

How to center slide-images with javascript?

I want to write my own jQuery slider, which shows a small part of the next and previous image (for example 20px).
To achieve this, I have created a simple image slider, using float: left; to arrange all the images in one row inside a overflow: hidden div.
All my images got a fixed width of 200px. Because of this I calculate the margins of each image with the following sass:
img {
float: left;
display: block;
margin: 0 calc((100vw - 200px) / 4 - 20px);
&:first-child {
margin-left: calc((100vw - 200px) / 2);
}
&:last-child {
margin-right: calc((100vw - 200px) / 2);
}
}
This works great and positions every image as it should be.
While trying to animate the slider using transform: translateX(); I am totally lost calculating the amount of pixels (in vw/%/px) I need to translateX the $('#slider').
How can I calculate the translateX value to slide to each image centered?
$(document).ready(function(){
document.getElementById('slider').ondragstart = function() { return false; };
var slider = $('#slider'),
images = slider.find('img'),
imageCount = images.length,
currentIndex = 0;
slider.width( imageCount * 100 + "vw");
var slideLeft = function () {
if ( currentIndex >= imageCount - 1 ) {
console.log("Last image reached");
return;
}
currentIndex += 1;
console.log("Slide left");
slider.css("transform", "translateX(" + currentIndex * -10 + "vw)");
}
var slideRight = function () {
if ( currentIndex === 0 ) {
console.log("First image reached");
return;
}
currentIndex -= 1;
console.log("Slide right");
slider.css("transform", "translateX(" + currentIndex * -10 + "vw)");
}
$('#right').on('click', function(){
slideLeft();
});
$('#left').on('click', function(){
slideRight();
});
});
html, body {
margin: 0;
padding: 0;
}
#slider-container {
overflow: hidden;
height: 300px;
background: rgba(0, 0, 0, 0.05);
margin: 5vw 0;
width: 100vw;
}
#slider {
height: 300px;
transition: transform .3s ease-in-out;
transform: translateX(0);
}
#slider img {
float: left;
display: block;
margin: 0 calc((100vw - 200px) / 4 - 20px);
}
#slider img:first-child {
margin-left: calc((100vw - 200px) / 2);
}
#slider img:last-child {
margin-right: calc((100vw - 200px) / 2);
}
#controls {
position: relative;
width: 100vw;
display: block;
height: calc(10vw + 100px);
}
#controls .arrow {
display: block;
width: 100px;
top: 5vw;
background: lightgray;
height: 100px;
left: 5vw;
position: absolute;
font-size: 100px;
line-height: 80px;
font-weight: bold;
text-align: center;
cursor: pointer;
}
#controls .arrow:hover {
background: lightblue;
}
#controls #right {
left: auto;
right: 5vw;
}
p {
margin: 0 5vw 5vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider-container">
<div id="slider">
<img src="https://unsplash.it/200/300?image=1077" alt="img-1">
<img src="https://unsplash.it/200/300?image=1076" alt="img-2">
<img src="https://unsplash.it/200/300?image=1072" alt="img-3">
<img src="https://unsplash.it/200/300?image=1063" alt="img-4">
<img src="https://unsplash.it/200/300?image=1061" alt="img-5">
</div>
</div>
<div id="controls">
<div id="left" class="arrow">‹</div>
<div id="right" class="arrow">›</div>
</div>
<p>Currently every scroll click scrolls a random amount to the left or right. This needs to be fixed, so that every image is centered after the slide.</p>
I had made few updates in your script.
try with this script
$(document).ready(function(){
document.getElementById('slider').ondragstart = function() { return false; };
var slider = $('#slider'),
images = slider.find('img'),
imageCount = images.length,
currentIndex = 0;
slider.width( imageCount * 100 + "vw");
var $this = $("#slider-container");
var offset = $this.offset();
var width = $this.width();
var centerX = (offset.left + width / 2 ) + (images.width() / 2) - 40;
var slideLeft = function () {
if ( currentIndex >= imageCount - 1 ) {
console.log("Last image reached");
return;
}
currentIndex += 1;
console.log("Slide left");
slider.css("transform", "translateX(-" + (currentIndex * centerX) + "px)");
}
var slideRight = function () {
if ( currentIndex === 0 ) {
console.log("First image reached");
return;
}
currentIndex -= 1;
console.log("Slide right");
slider.css("transform", "translateX(-" + (currentIndex * centerX) + "px)");
}
$('#right').on('click', function(){
slideLeft();
});
$('#left').on('click', function(){
slideRight();
});
});
check this fiddle : jsFiddle

Crossfade 3+ images with js / jQuery

I'm stuck with a crossfade. My images fade into black, but I have no idea how to rework this to have crossfade.
var backgroundClasses = ['bg1', 'bg2']; // Store all the background classes defined in your css in an array
var $element = $('.container'); // cache the element we're going to work with
var counter = 0; // this variable will keep increasing to alter classes
setInterval(function() { // an interval
counter++; // increase the counter
$element.fadeOut(500, function() { // fade out the element
$element.removeClass(backgroundClasses.join(' ')). // remove all the classes defined in the array
addClass(backgroundClasses[counter % backgroundClasses.length]). // add a class from the classes array
fadeIn(500); // show the element
});
}, 3000)
.container {
width: 100vw;
height: 100vh;
}
.bg1 {
background-color: red;
}
.bg2 {
background-color: green;
}
This could be better achieved with CSS.
$(document).ready( function()
{
var counter = 1;
setInterval( function()
{
// current
var current = '.bg' + counter % $('.bg').length;
counter++;
var next = '.bg' + counter % $('.bg').length;
$( current ).addClass('bg-fadeout');
$( next ).removeClass('bg-fadeout');
}, 1000);
})
.bgs {
position: relative;
}
.bg {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
opacity: 1;
transition: opacity 0.3s linear;
}
.bg-fadeout {
opacity: 0;
}
.bg1, .bg3 {
background-color: red;
}
.bg4, .bg2 {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bgs">
<div class="bg bg4"></div>
<div class="bg bg3"></div>
<div class="bg bg2"></div>
<div class="bg bg1"></div>
<div>

restart animation jquery and javascript

Hi i'm creating a jquery slider and i'm having problems to restar the slider when the time(in the setInterval) is over. When the 3 images slide and the last one is showing the animation stays there, but i want to restart to the first image and start the loop again. Could someone help me?
Thanks!
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Slider Jquery Test</title>
<link href="slider.css" rel="stylesheet" type="text/css">
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/slidertest.js"></script>
</head>
<body>
<div id="container">
<ul id="buttons" class="buttons">
<li><img id="left_b" class="left_b" src="imagens/flechae.png" alt="Anterior" onMouseOver="this.src='imagens/flechaehover.png'" onMouseOut="this.src='imagens/flechae.png'"></li>
<li><img id="right_b" class="right_b" src="imagens/flechad.png" alt="Proximo" onMouseOver="this.src='imagens/flechadhover.png'" onMouseOut="this.src='imagens/flechad.png'"></li>
</ul>
<ul id="gallery" class="gallery">
<li><img id="1" class="images" src="imagens/imagem1.jpg" alt="Imagem 1"></li>
<li><img id="2" class="images" src="imagens/imagem2.jpg" alt="Imagem 2"></li>
<li><img id="3" class="images" src="imagens/imagem3.jpg" alt="Imagem 3"></li>
</ul>
</div>
</body>
</html>
CSS
#charset "utf-8";
body{
width: 100%;
height: auto;
}
#container {
width: 100%;
height: auto;
margin: 0;
padding: 0;
/*overflow: hidden;*/
}
.buttons {
width: 100%;
height: auto;
list-style: none;
margin: 0;
padding: 0;
position: absolute;
z-index: 1;
display: none;
}
.buttons li {
width: 100%;
height: auto;
position: relative;
margin: 0;
padding: 0;
}
.left_b {
width: 20px;
height: 80px;
position: relative;
float: left;
margin-left: 30px;
margin-top: 250px;
}
.right_b {
width: 20px;
height: 80px;
position: relative;
float: right;
margin-right: 30px;
margin-top: 250px;
}
.gallery {
width: 100%;
height: auto;
list-style: none;
margin: 0;
padding: 0;
position: relative;
overflow: hidden;
}
.gallery li {
width: auto;
height: auto;
position: relative;
float: left;
}
.images {
width: 1200px;
height: 720px;
position: relative;
float: left;
}
JavaScript
$(function(){
slide();
// Slider
function slide()
{
// Variables
var interval = 0;
var time = 3000;
var seconds = 1000;
var current_image = 1;
var num_images = 0;
var total_width = 0;
var slide_left = "+=1200px";
var slide_right = "-=1200px";
var right_b = $(".right_b");
var left_b = $(".left_b");
var left = "margin-left";
var width = "width";
var gallery = $(".gallery");
var galleryLi = $(".gallery li");
var images = $(".images");
var buttons_class = $(".buttons");
var container = $("#container");
// Calling functions
imagesSize();
hideButtons();
animation();
// Functions
function animation()
{
if(current_image < num_images)
{
loop();
clickRight();
clickLeft();
}
}
function hideButtons()
{
container.hover(function(){
buttons_class.fadeIn();
}, function(){
buttons_class.fadeOut();
});
}
function imagesSize()
{
galleryLi.each(function(){
num_images++;
total_width += 1200;
});
gallery.css(width, total_width + "px");
}
function loop()
{
if(current_image >= 1){
interval = setInterval(moveLeft, time);
}
else if(current_image === num_images){
clearLoop();
moveLeft();
}
}
function clearLoop()
{
clearInterval(interval);
}
function moveLeft()
{
if(current_image < num_images){
gallery.animate({left: slide_right}, seconds);
current_image++;
}
}
function clickRight()
{
right_b.click(function(){
moveLeft();
clearLoop();
loop();
});
}
function moveRight()
{
if(current_image > 1){
gallery.animate({"margin-left": slide_left}, seconds);
current_image--;
}
}
function clickLeft()
{
left_b.click(function(){
moveRight();
clearLoop();
loop();
});
}
} // end of function slide
}); // End of main function
function loop()
{
if(current_image >= 1){
interval = setInterval(moveLeft, time);
}
else if(current_image === num_images){
clearLoop(); // Clear the previous interval
moveLeft();
// Add these two lines after setTimeout to finish the animation.
setTimeout(function(){
current_image = 1;
loop();
}, seconds);
}
}

Categories