Reset Javascript Timer for Image Slider - javascript

I am creating an image slider and using a JavaScript timer to advance to the next picture. When the user clicks on the forward or back button (see picture below) the time the slide is displayed decreases greatly. I need help making the buttons advance the slide and reset the timer and the same time. I am attaching my JavaScript, HTML, and CSS to cover my code thoroughly.
My JavaScript:
var imageShown = 1;
var total = 7;
function autoplay() {
var image = document.getElementById('picture');
imageShown = imageShown + 1;
if(imageShown > total){imageShown = 1;}
if(imageShown < 1){imageShown = total;}
picture.src = "Images/img"+ imageShown +".jpg";
console.log("Pic Changed");
}
window.setInterval(autoplay, 5000);
function pic(x) {
var image = document.getElementById('picture');
imageShown = imageShown + x;
if(imageShown > total){imageShown = 1;}
if(imageShown < 1){imageShown = total;}
picture.src = "Images/img"+ imageShown +".jpg";
console.log("Button clicked");
window.clearInterval(autoplay);
window.setInterval(autoplay, 5000);
}
My HTML:
<img src="Images/img1.jpg" id="picture" >
<div class="left_div"><img onClick="pic(-1)" class="left_click" src="Images/left.png"></div>
<div class="right_div"><img onClick="pic(+1)" class="right_click" src="Images/right.png"></div>
</div>
My CSS:
margin:0px;
}
#imageslider {
height:700px;
width:1000px;
margin: 50px auto;
position:absolute;
border-radius:4px;
overflow:hidden;
padding-right: 5000px;
padding-top: 1000px;
}
#picture {
height:750px;
width:1000px;
position:relative;
padding-top: 50px
}
.left_div {
height: 750px;
width: 150px;
position: absolute;
top: 250px;
left: 0px;
}
.right_div {
height: 750px;
width: 150px;
position: absolute;
top: 250px;
right: 0px;
}
.left_click {
height:50px;
width:50px;
position:absolute;
top:40%;
left:20px;
opacity:0;
transition: all .2s ease-in-out 0s;
}
.right_click {
height:50px;
width:50px;
position:absolute;
top:40%;
right:20px;
opacity:0;
transition: all .5s ease-in-out 0s;
}
.left_div:hover .left_click {
opacity:0.6;
}
.right_div:hover .right_click {
opacity:0.6;
}
.left:hover .left1

You should use clearInterval as following:
clearInterval(autoplay);
or as
window.clearInterval(autoplay);

I think that you might be trying to reset the interval incorrectly
http://www.w3schools.com/jsref/met_win_clearinterval.asp this gives an example of how to reset a function set to an interval in javascript

Related

How can I loop setTimeout slideshow javascript

on function start(){ my javascript I want my slideshow to be like when It start, It would wait for 2s, then It should go to (slide2) first with setTimeout(slide2, 2000); without waiting for so long with '8 second' from }, 8000);.
then It would go to (slide3) with setTimeout(slide3, 4000); (It means wait for 2s per slide) then (slide3) at the last slide, It should go back to (slide1) to star loop again.. //Code-on-JsFiddle//
or any simple way to write javascript loop you would like to suggest.
var div = document.getElementsByClassName('content')[0];
var box = document.getElementsByClassName('box')[0];
var u = -100;
function slide1(){
box.style.marginLeft = '0';}
function slide2(){
box.style.marginLeft = '-100px';}
function slide3(){
box.style.marginLeft = '-200px';}
function start() {
setTimeout(function() {
setTimeout(slide2, 2000);
setTimeout(slide3, 4000);
setTimeout(slide1, 6000);
start();
}, 8000);
}
start();
body { margin:0; padding:0;}
.content { width: 100px; height:60px; margin:5px 0px;
overflow:hidden; white-space:nowrap; background: lightgray;
display: inline-block; position: relative;
border:2px solid black; }
.box { width: 100px; height: 50px; display: inline-block;
position: relative; border:1px solid black; margin:0px;
background:lightblue; transition: all 0.5s ease; }
.button { padding:5px; border:1px solid black; background:pink;
display:inline-block; }
<body>
<div class='content'>
<div class='box'>1</div>
<div class='box'>2</div>
<div class='box'>3</div>
</div>
<br/>
<div class='button' onclick='slide1();'>1</div>
<div class='button' onclick='slide2();'>2</div>
<div class='button' onclick='slide3();'>3</div>
</body>
I think your approach with multiple functions is not a good idea. Keeping as much of your code as possible, this re-write is a lot more expandable.
var div = document.getElementsByClassName('content')[0];
var box = document.getElementsByClassName('box')[0];
var u = -100;
var slideIdx = 0;
var delay;
function slide(idx){
//console.log("slide, slideIdx:["+ slideIdx +"], idx:["+ idx +"]");
if (delay){
clearTimeout(delay);
delay=null;
}
if (idx){
slideIdx = (idx > 2) ? 0 : idx;
} else {
slideIdx++;
}
slideIdx = (slideIdx > 2) ? 0 : slideIdx;
box.style.marginLeft = (-100 * slideIdx) +"px";
delay = setTimeout(slide,2000);
}
delay = setTimeout(slide,2000);
.content {box-sizing:border-box;width:100px;height:60px;margin:5px 0px;
overflow:hidden;white-space:nowrap;background:lightgray;
display:inline-block;position:relative;border:2px solid black}
.box {box-sizing:border-box;width:100px;height:50px;display:inline-block;position:relative;
border:1px solid black;margin:0px;background:lightblue;
transition: all 0.5s ease}
.button { padding:5px; border:1px solid black; background:pink;
display:inline-block;}
<body>
<div class='content'><div
class='box'>1</div><div class='box'>2</div><div
class='box'>3</div></div>
<br/>
<div class="button" onclick="slide(0)">1x</div>
<div class="button" onclick="slide(1)">2x</div>
<div class="button" onclick="slide(2)">3x</div>
</body>

Delay random position jQuery

I have some code that displays 4 divs at a random hight at specified distances from the viewport sides, each div appears with a different delay speed and then moves around the page at random.
I want to add a delay to the movement of each div so they don't all start and stop moving at the same time but every time I add ad .delay() it breaks. Any help?
Thanks
HTML
<div class="content">
<div class="loopbox">
<div id="rand_pos" class="loop mobile box1">L</div>
<div id="rand_pos" class="loop mobile box2">O</div>
<div id="rand_pos" class="loop mobile box3">O</div>
<div id="rand_pos" class="loop mobile box4">P</div>
</div>
<div class="info">
<h1>COMING SOON</h1>
<p>info#loopstudio.uk</p>
</div>
</div>
*CSS
#import url('https://fonts.googleapis.com/css?family=Marcellus&display=swap');
*:focus {
outline: none;
}
html { overflow: hidden; }
body {
margin: 0;
background-color:#FFF9F3;
}
p,h1 {
font-family:sans-serif;
}
h1{
font-weight:100;
}
.loop {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
font-size:22vw;
font-family:'Marcellus', serif;
font-weight:100;
color: black;
position: absolute;
}
.loop:hover {
animation: shake 0.82s cubic-bezier(.5,.01,.01,.05) 1;
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
perspective: 1000px;
-webkit-animation-fill-mode:forwards;
-moz-animation-fill-mode:forwards;
animation-fill-mode:forwards;
}
.box1{
top:10vh;
left:8vw;
display:none;
}
.box2{
top:20vh;
left:30vw;
display:none;
}
.box3{
top:30vh;
right:35vw;
display:none;
}
.box4{
top:40vh;
right:10vw;
display:none;
}
.content {
position: relative;
height: 100vh;
width: 100vw;
margin: 0 auto;
resize: both;
}
.info {
width: 100%;
height:auto;
transform: translate(-50%, -50%);
position: fixed;
top: 50%;
left: 50%;
resize: both;
text-align:center;
z-index:-1000;
}
JS
$('document').ready(function(){
$('.box1').delay(500).fadeIn(850);
$('.box2').delay(1000).fadeIn(850);
$('.box3').delay(750).fadeIn(850);
$('.box4').delay(1250).fadeIn(850);
});
$('document').ready(function() {
var bodyHeight = document.body.clientHeight;
var randPosY = Math.floor((Math.random()*bodyHeight));
$('#rand_pos').css('top', randPosY);
});
$(document).ready(function(){
animateDiv('.box1');
animateDiv('.box2');
animateDiv('.box3');
animateDiv('.box4');
});
function makeNewPosition(){
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(myclass){
var newq = makeNewPosition();
$(myclass).animate({ top: newq[0], left: newq[1] }, 8000, function(){
animateDiv(myclass);
});
};

Javascript is having problems with moving divs around

Here's a function:
function rollImgOnSwipe(direction) {
changeDirection(direction);
rollImage(direction);
}
The first called function (changeDirection(direction);) is supposed to place a div in either the left or right side of the screen, depending on the value of its argument. The second one (rollImage(direction);) is to make the div move from left to right or from right to left, depending on where the first function placed it.
Well, it seems like it first calls rollImage and then changeDirection because it takes rollImgOnSwipe to be called more than once in order for the div to be placed on the other side.
The best way to explain this to you is to show you - run the code snippet and try switching between the divs with the prev and next buttons and see how they behave.
var nextBtn = document.getElementById('next'),
prevBtn = document.getElementById('prev'),
shown = document.getElementsByClassName('shown')[0],
hidden = document.getElementsByClassName('hidden')[0];
function rollImage(direction) {
shown.classList.remove("shown");
shown.classList.add("hidden");
hidden.classList.remove("hidden");
hidden.classList.add("shown");
shown = document.getElementsByClassName('shown')[0];
hidden = document.getElementsByClassName('hidden')[0];
changeDirection(direction);
}
function rollImgOnSwipe(direction) {
changeDirection(direction);
rollImage(direction);
}
function changeDirection(direction) {
hidden.style.left = (105 * direction) + "%";
shown.style.left = 0;
}
nextBtn.addEventListener('click', function () { rollImgOnSwipe(1); });
prevBtn.addEventListener('click', function () { rollImgOnSwipe(-1); });
.img {
position: absolute;
display: block;
width: 80px;
height: 30px;
border-style: solid;
border-color: red;
border-width: 5px;
}
.shown{
left: 0;
transition: left .6s ease, transform .6s ease;
}
.hidden{
left: 105%;
}
.img-wrapper{
position: relative;
width: 80px;
height: 30px;
padding: 30px;
white-space: nowrap;
overflow: hidden;
}
<button id="prev">prev</button>
<div class="img-wrapper">
<div class="img shown"></div>
<div class="img hidden"></div>
</div>
<button id="next">next</button>
To fix this, i make the compiler wait for a bit before calling rollImage by using the setTimeout function in rollImgOnSwipe.
And now the program works as expected:
var nextBtn = document.getElementById('next'),
prevBtn = document.getElementById('prev'),
shown = document.getElementsByClassName('shown')[0],
hidden = document.getElementsByClassName('hidden')[0];
function rollImage(direction) {
shown.classList.remove("shown");
shown.classList.add("hidden");
hidden.classList.remove("hidden");
hidden.classList.add("shown");
shown = document.getElementsByClassName('shown')[0];
hidden = document.getElementsByClassName('hidden')[0];
changeDirection(direction);
}
function rollImgOnSwipe(direction) {
changeDirection(direction);
setTimeout(function() { rollImage(direction); }, 50);
}
function changeDirection(direction) {
hidden.style.left = (105 * direction) + "%";
shown.style.left = 0;
}
nextBtn.addEventListener('click', function(){ rollImgOnSwipe(1); });
prevBtn.addEventListener('click', function(){ rollImgOnSwipe(-1); });
.img {
position: absolute;
display: block;
width: 80px;
height: 30px;
border-style: solid;
border-color: red;
border-width: 5px;
}
.shown{
left: 0;
transition: left .6s ease, transform .6s ease;
}
.hidden{
left: 105%;
}
.img-wrapper{
position: relative;
width: 80px;
height: 30px;
padding: 30px;
white-space: nowrap;
overflow: hidden;
}
<button id="prev">prev</button>
<div class="img-wrapper">
<div class="img shown"></div>
<div class="img hidden"></div>
</div>
<button id="next">next</button>
My question is:
What is the problem and why is it fixed by making the compiler wait?

jQuery animate element to go left

I'm trying to animate an element to move: left:0px but It doesn't seem to work. I surmise the issue is that the element isn't absolute positioned but how would I do that with animate?
fid: https://jsfiddle.net/jzhang172/j2yrumyg/8/
$(function(){
var cheese= $('.ok').offset().top; //Define top of 'hey'
//
//Animates when it reaches red part of page
//
$(window).scroll(function() {
if ( $(window).scrollTop() >= cheese ) {
$('.ok').addClass('top');
$('.nice').hide().fadeIn().html('ok');
$(".nice").animate({
left:"0"
}, 600);
$('.nice').addClass('maybe');
}
else{
$('.ok').removeClass('top');
$('.nice').removeClass('maybe');
$('.nice').html('Hey');
}
});
//
//This part doesn't rely on scroll event and is in charge of changing hover on ".ok" div.
//
$('.ok').hover(function(){
if(!$(this).hasClass("top"))
$(this).addClass('proj-hover');
},function(){
$(this).removeClass('proj-hover');
});
//
//Animate on click
//
$('.ok').click(function(){
if ( $(window).scrollTop() >= cheese ) {
}
else{
$("body, html").animate({
scrollTop: $('.other').offset().top
}, 600);
}
});
});
*{
box-sizing:border-box;
}
body,html{
padding:0;
margin:0;
}
.div{
height:100vh;
width:100%;
background:#6464FF;
}
.other{
height:1000px;
width:100%;
background:#FF6161;
}
.ok{
position:absolute;
bottom:0;
left:50%;
margin-left:-100px;
width:200px;
height:50px;
line-height:50px;
background:black;
color:white;
text-align:center;
transition:1s;
}
.top{
position:fixed;
top:0;
left:0;
transition:.7s;
margin-left: 0px;
width:100%;
}
.proj-hover{
background:white;
color:black;
}
.blue{
background:blue;
}
.nice{
transition:0s;
margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
<div class="ok">
<p class="nice">Hey</p>
</div>
</div>
<div class="other">
</div>
To move the text to the left, which is centered by a text-alignment property, you have to change the width of the container. I did the animation with CSS3 by adding some css and removing the jquery animation of the element nice :
.nice {
margin: 0px;
width: 100%;
transition: width .6s;
}
.maybe {
width: 0;
}
Here the complete code:
$(function() {
var cheese = $('.ok').offset().top; //Define top of 'hey'
//
//Animates when it reaches red part of page
//
$(window).scroll(function() {
if ($(window).scrollTop() >= cheese) {
$('.ok').addClass('top');
//$(".nice").animate({
// width: '0%'
//}, 600).css('overflow', '');
$('.nice').addClass('maybe');
} else {
$('.ok').removeClass('top');
$('.nice').removeClass('maybe');
$('.nice').html('Hey');
}
});
//
//This part doesn't rely on scroll event and is in charge of changing hover on ".ok" div.
//
$('.ok').hover(function() {
if (!$(this).hasClass("top"))
$(this).addClass('proj-hover');
}, function() {
$(this).removeClass('proj-hover');
});
//
//Animate on click
//
$('.ok').click(function() {
if ($(window).scrollTop() >= cheese) {
} else {
$("body, html").animate({
scrollTop: $('.other').offset().top
}, 600);
}
});
});
* {
box-sizing: border-box;
}
body,
html {
padding: 0;
margin: 0;
}
.div {
height: 100vh;
width: 100%;
background: #6464FF;
}
.other {
height: 1000px;
width: 100%;
background: #FF6161;
}
.ok {
position: absolute;
bottom: 0;
left: 50%;
margin-left: -100px;
width: 200px;
height: 50px;
line-height: 50px;
background: black;
color: white;
text-align: center;
transition: 1s;
}
.top {
position: fixed;
top: 0;
left: 0;
transition: .7s;
margin-left: 0px;
width: 100%;
}
.proj-hover {
background: white;
color: black;
}
.blue {
background: blue;
}
.nice {
transition: 0s;
margin: 0px;
width: 100%;
transition: width .6s;
}
.maybe {
width: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
<div class="ok">
<p class="nice">Hey</p>
</div>
</div>
<div class="other">
</div>
Not sure if I understand your question. The "ok" should move to the left?
You have declared width:100%; in your CSS class top. So it is already left. Remove it and it will work.
Or you might want within the .nice class:
position:absolute;
left:0; right:0;
margin: auto;
and do a
$(".nice").animate({
right:"100%"
}, 600);

Implement nav dots to my slider?

I've been messing around with my slider and I got it to slide by itself. The problem is, there is no way you can manually view the slides. I would like to add navigation dots on the bottom so you can skim through the slides without having to view them as the slider goes along. If you could help me with this it would be greatly appreciated.
My slider html:
<div id="slider-container">
<div style="position: relative">
<div class="slide"><img id="slide_1" src="images/slide_1.jpg"/></div>
<div class="slide"><img id="slide_2" src="images/slide_2.jpg"/></div>
<div class="slide"><img id="slide_3" src="images/slide_3.jpg"/></div>
<div class="slide"><img id="slide_4" src="images/slide_4.jpg"/></div>
<div class="slide"><img id="slide_5" src="images/slide_5.jpg"/></div>
<div class="slide"><img id="slide_6" src="images/slide_6.jpg"/></div>
</div>
</div>
My slider css:
.slide-container {
display:block;
}
.slide {
top:0;
width:760px;
height:420px;
display:block;
position:absolute;
transform:scale(0);
transition:all .7s;
}
.slide img {
width:100%;
height:100%;
border-radius:6px;
border:1px solid #95ca1a;
}
My slider javascript:
$(document).ready(function() {
(function (){
var count = $(".slide > img").length;
var current = 1;
var sliderNext = 2;
$("img[id^='slide_']").fadeOut(0);
$("#slide_" + current).fadeIn(300);
var loop = setInterval(function() {
$("#slide_" + current).fadeOut(300);
$("#slide_" + sliderNext).fadeIn(300);
(sliderNext >= count) ? sliderNext = 1 : sliderNext++;
(current >= count) ? current = 1 : current++;
}, 3000)
})()
});
Here's an example of what I mean by nav dots:
CSS Slider - Codepen
First create list of dots, you can do it manually by creating list of "li" tags or can create it via jQuery.
here is code
<ol>
<li></li>
<li></li>
<li></li>
</ol>
number of "li" element should match with number of images
then have following css
#slider-container {
position:relative;
overflow:hidden;
width:100%;
height:380px;
display:inline-block;
}
.slide {
top:0;
width:100%;
display:inline-block;
}
.slide img {
width:100%;
height:100%;
border-radius:6px;
border:1px solid #95ca1a;
}
/******* css of dots ****/
ol{
list-style= none;
width:100%;
}
ol li{
background: #888;
border-radius: 50%;
display: inline-block;
width:20px;
height:20px;
cursor: pointer;
}
then add following jQuery stuff
$('ol li').bind('click', function(){
var index = $(this).index() + 1;
$(".active").fadeOut(300);
$("#slide_" + index).fadeIn(300);
$(".slide").removeClass("active");
$("#slide_" + index).addClass("active");
});
this code will hide active image and shows selected image
here is Fiddle example
hope it will help you
Here is a carousel script I wrote for a project. This allows you to click forward and backward and also on the dots. It's also dynamic so if you have 1 image, there are no dots or scroll bars, if you have 2 images there are the bars to go right and left but no dots, once you have three or more images the dots will be applied.
JsFiddle
HTML
<div class="carousel-container">
<div class="left-arrow"></div>
<div class="right-arrow"></div>
<div class="carousel-image-holder">
<img src="http://digitaljournal.com/img/8/7/8/4/4/i/1/1/7/o/ulingan_kids.jpg" />
<img src="http://freethoughtblogs.com/taslima/files/2012/06/22-funny2.jpg" />
<img src="http://blog.metrotrends.org/wp-content/uploads/2013/09/childPoverty.jpg" />
<img src="http://www.chinadaily.com.cn/china/images/2010WenUN/attachement/jpg/site1/20100921/0013729ece6b0e01d9691a.jpg" />
</div>
</div>
<div class="clear"></div>
<div class="carousel-buttons-container">
<ul></ul>
</div>
CSS
.clear{clear:both;}
.carousel-container{
width: 600px;
height: 360px;
float: left;
margin: 0;
padding: 0;
position: relative;
overflow: hidden;
}
.right-arrow{
width: 60px;
height: 100%;
background-color: rgba(0,0,0,.5);
position: absolute;
right: 0;
margin: 0;
padding: 0;
z-index: 2;
}
.left-arrow{
width: 60px;
height: 100%;
background-color: rgba(0,0,0,.5);
position: absolute;
left: 0;
margin: 0;
padding: 0;
z-index: 2;
}
.carousel-image-holder{
height:360px;
width: 2400px;
margin: 0;
padding: 0;
position: absolute;
z-index: 1;
}
.carousel-image-holder img{
width: 600px;
float: left;
margin: 0;
padding: 0;
display: inline-block;
}
.carousel-buttons-container{
width: 600px;
text-align: center;
margin: 15px 0 0 0;
padding: 0;
}
.carousel-buttons-container ul{
list-style-type: none;
margin: 0;
padding: 0;
}
.carousel-buttons{
background-color: #dddddd;
height: 18px;
width: 18px;
border-radius: 50%;
display: inline-block;
margin: 0 10px 0 0;
padding: 0;
cursor: pointer;
}
.carousel-buttons:last-of-type{
margin: 0;
}
.active{
background-color: #e67e22;
}
JQUERY
$(".left-arrow").hide();
var numImgs = $('div.carousel-image-holder img').length;
var addId = numImgs;
if(numImgs == 2){
var clicked = 0;
imgCount = numImgs-2;
}else if(numImgs <= 1){
$(".right-arrow").hide();
}else{
var clicked = 1;
imgCount = numImgs-1;
}
if(numImgs > 2){
for (var i=0; i<numImgs; i++){
$("ul").prepend('<li class="carousel-buttons" id="carousel'+addId+'"></li>');
var addId = addId - 1;
}
}else{
}
$(".carousel-buttons").click(function(){
var findIdClicked = $(this).attr("id");
var splitString = findIdClicked.split("carousel")
var findTheNumb = splitString[1];
$(".carousel-buttons").removeClass("active");
$(this).addClass("active");
clicked = parseInt(findTheNumb);
var adjustNumberforSlide = findTheNumb-1;
$(".carousel-image-holder").animate({"left": -(600*adjustNumberforSlide)+"px"});
console.log(clicked);
if(findTheNumb == 1){
$(".left-arrow").hide();
$(".right-arrow").show();
}else if (findTheNumb == numImgs){
$(".right-arrow").hide();
$(".left-arrow").show();
}else{
$(".right-arrow").show();
$(".left-arrow").show();
}
});
$(".carousel-buttons-container").find("li").first().addClass("active");
$(".right-arrow").click(function(){
if (clicked < imgCount){
$(".carousel-image-holder").animate({"left": "-=600px"});
console.log(clicked);
}else{
$(".carousel-image-holder").animate({"left": "-=600px"});
$(".right-arrow").hide();
console.log(clicked);
}
clicked = clicked+1;
$(".left-arrow").show();
$(".carousel-buttons").removeClass("active");
$("#carousel"+clicked).addClass("active");
});
$(".left-arrow").click(function(){
if (clicked > 2){
$(".carousel-image-holder").animate({"left": "+=600px"});
console.log(clicked);
}else{
$(".carousel-image-holder").animate({"left": "+=600px"});
$(".left-arrow").hide();
console.log(clicked);
}
$(".right-arrow").show();
clicked = clicked-1;
$(".carousel-buttons").removeClass("active");
$("#carousel"+clicked).addClass("active");
});
I'll clean up the spacing, just wanted to get this posted

Categories

Resources