Implementing Autoplay on glider.js - javascript

So I'm working with glider.js (https://nickpiscitelli.github.io/Glider.js/) on my website for handling slides, because I really want to keep it minimal (I know there are other sliders out there, but glider.js is the lightest). However, I really need the autoplay function, but I can't seem to be able to make it work (I don't really know my way around JS, I just copy code snippets for things I need)
I found some code for an autoplay, it looks like this:
function sliderAuto(slider, miliseconds) {
slider.isLastSlide = function() {
return slider.page >= slider.dots.childElementCount - 1;
}
var slide = function() {
slider.slideTimeout = setTimeout(function() {
function slideTo() {
return slider.isLastSlide() ? 0 : slider.page + 1;
}
slider.scrollItem(slideTo(), true);
}, miliseconds);
}
slider.ele.addEventListener('glider-animated', function(event) {
window.clearInterval(slider.slideTimeout);
slide();
});
slide();
}
But I don't know how to activate it, to make it work. I know I should pass the parameters to "slider" and "miliseconds", but I don't know what exactly should I pass, should I set a special class to each slide, and pass that class? Let's say my html is the following:
<div class="glider-contain">
<div class="glider">
<div>your content here</div>
<div>your content here</div>
<div>your content here</div>
<div>your content here</div>
</div>
How do I make the autoplay work? Thanks!

Based on the docs that you've linked and the code snippet i would say that
First things first, slider parameter is supposed to be your glidder object (what you created with new Glidder(..., and milliseconds is the amount of time in milliseconds that each slide will be visible.
Now, an example of what it could look like:
<div class="glider-contain">
<div id="glider" class="glider">
<div class="placeholder">1</div>
<div class="placeholder">2</div>
<div class="placeholder">3</div>
<div class="placeholder">4</div>
</div>
</div>
const glider = new Glider(document.getElementById('glider'));
function sliderAuto(slider, miliseconds) {
const slidesCount = slider.track.childElementCount;
let slideTimeout = null;
let nextIndex = 1;
function slide () {
slideTimeout = setTimeout(
function () {
if (nextIndex >= slidesCount ) {
nextIndex = 0;
}
slider.scrollItem(nextIndex++);
},
miliseconds
);
}
slider.ele.addEventListener('glider-animated', function() {
window.clearInterval(slideTimeout);
slide();
});
slide();
}
sliderAuto(glider, 1000)
I've edited the snippet a bit because you don't seem to use dots.
working fiddle

I have tweaked the accepted answer to pause autoplay on mouse hover. In addition, you can handle autoplay loop with the repeat argument of the slideAutoPaly function.
var slider = new Glider(document.querySelector('.glider'), {
slidesToScroll: 1,
slidesToShow: 1,
dots: '#dots',
arrows: {
prev: '.glider-prev',
next: '.glider-next'
}
});
slideAutoPaly(slider, '.glider');
function slideAutoPaly(glider, selector, delay = 5000, repeat = true) {
let autoplay = null;
const slidesCount = glider.track.childElementCount;
let nextIndex = 1;
let pause = true;
function slide() {
autoplay = setInterval(() => {
if (nextIndex >= slidesCount) {
if (!repeat) {
clearInterval(autoplay);
} else {
nextIndex = 0;
}
}
glider.scrollItem(nextIndex++);
}, delay);
}
slide();
var element = document.querySelector(selector);
element.addEventListener('mouseover', (event) => {
if (pause) {
clearInterval(autoplay);
pause = false;
}
}, 300);
element.addEventListener('mouseout', (event) => {
if (!pause) {
slide();
pause = true;
}
}, 300);
}
Also, check the Github issue: https://github.com/NickPiscitelli/Glider.js/issues/43

Related

How do I rewrite this JavaScript to include extra event listeners?

I'm using a script I found online which controls page transitions using GSAP (Greensock).
I'm no expert but I've followed some tutorials soI kinda get the GSAP part.
My problem is this script toggles 2 page transitions - click on button 1 and page 2 animates into view. Now click on button 2 and page one returns.
I'm trying to extend this script to include extra pages (with extra buttons). I've tried a few times but so far I'm getting nowhere.
The script I'm using is:
var btns = document.querySelectorAll('.jsBtn');
var duration = .8;
var isAnimating = false;
addEventListenerList(btns, 'click', function (e) {
if(!isAnimating) {
switchPages(e.currentTarget.dataset.out, e.currentTarget.dataset.in);
}
});
function switchPages(outFn, inFn) {
isAnimating = true;
window[outFn](document.querySelector('.current'));
window[inFn](document.querySelector('.jsPage:not(.current)'));
}
function scaleDown(el) {
addClass(el, 'current');
TweenLite.fromTo(el, duration, {
opacity: 1,
scale: 1
}, {
opacity: 0,
scale: .8,
clearProps: 'opacity, scale',
onComplete: function () {
removeClass(el, ['top', 'current']);
}
});
}
function moveFromRight(el) {
addClass(el, ['top', 'current']);
TweenLite.fromTo(el, duration, {
xPercent: 100
}, {
xPercent: 0,
clearProps: 'xPercent',
onComplete: function () {
removeClass(el, 'top');
isAnimating = false;
}
});
}
// utils
function addClass(el, className) {
[].concat(className).forEach(function (n) {
el.classList.add(n);
});
}
function removeClass(el, className) {
[].concat(className).forEach(function (n) {
el.classList.remove(n);
});
}
function addEventListenerList(list, event, fn) {
for (var i = 0, len = list.length; i < len; i++) {
list[i].addEventListener(event, fn, false);
}
}
The HTML I'm using is as follows. I have inserted a third page (and third button) but cannot get the script to recognise this button and trigger the relevant transition:
<div class="page p1 current jsPage">
<button class="btn1 jsBtn" data-out="scaleDown" data-in="moveFromRight">One</button>
</div>
<div class="page p2 jsPage">
<button class="btn2 two jsBtn" data-out="scaleDown" data-in="moveFromRight">Two</button>
</div>
<div class="page p3 jsPage">
<button class="btn3 three jsBtn" data-out="scaleDown" data-in="moveFromRight">Two</button>
</div>
Hoping someone can show me how to rewrite/extend this script.
Thanks.
switchPages function is probably where you want to make changes.
here is an example:
function switchPages(outFn, inFn) {
isAnimating = true;
var currentPage = document.querySelector('.current'); // get current page
var nextPage = currentPage.nextElementSibling; // get next page, assuming identical html structure
if (!nextPage.classList.contains('jsPage')) nextPage = document.querySelector('.jsPage'); // if next element is not a page, get first page
window[outFn](currentPage); // does it need to be global?
window[inFn](nextPage); // does it need to be global?
}

How can I reset the timer again using clearInterval()?

I have looked at the other threads about this question, but so far I have found no solution that fits my problem. I want to create a timer that activates using an addEventListener, in which I will use a setInterval(). Then I want to have a "pause" button that can pause the setInterval(), which I did by using clearInterval().
My problem is that, once I pause my timer once, I cannot get the timer to continue counting again by clicking the same button that starts the timer in the first place. This is my code:
hour=document.getElementById("hour");
minute=document.getElementById("minute");
second=document.getElementById("second");
start=document.getElementById("start")
reset=document.getElementById("reset")
pause=document.getElementById("pause");
var countdown;
start.addEventListener("click", function clicked() {
countdown = setInterval(function() {
if (second.textContent!="59") {
let new_second=Number(second.textContent)+1;
second.textContent=new_second;
}
else {
second.textContent="00";
if (minute.textContent!="59") {
let new_minute=Number(minute.textContent)+1;
minute.textContent=new_minute;
}
else {
minute.textContent="00";
let new_hour=Number(hour.textContent)+1;
hour.textContent=new_hour;
}
}
}, 1000)
this.outerHTML=this.outerHTML;
}, false);
pause.addEventListener("click", function() {
clearInterval(countdown);
})
reset.addEventListener("click",function() {
clearInterval(countdown);;
second.textContent="00";
minute.textContent="00";
hour.text.Content="00";
})
Thank you all for your help!
outerHTML destroys the original start button (and creates a new instance), and thus the event listener you attached to it is no longer valid. Fixed code here:
hour=document.getElementById("hour");
minute=document.getElementById("minute");
second=document.getElementById("second");
start=document.getElementById("start")
reset=document.getElementById("reset")
pause=document.getElementById("pause");
var countdown;
start.addEventListener("click", function clicked() {
// alternatively you can clearInterval here every time
if(!countdown)
countdown = setInterval(function() {
if (second.textContent!="59") {
let new_second=Number(second.textContent)+1;
second.textContent=new_second;
}
else {
second.textContent="00";
if (minute.textContent!="59") {
let new_minute=Number(minute.textContent)+1;
minute.textContent=new_minute;
}
else {
minute.textContent="00";
let new_hour=Number(hour.textContent)+1;
hour.textContent=new_hour;
}
}
}, 1000)
}, false);
pause.addEventListener("click", function() {
clearInterval(countdown);
countdown=null;
})
reset.addEventListener("click",function() {
clearInterval(countdown);
countdown=null;
second.textContent="00";
minute.textContent="00";
hour.textContent="00";
})
<div id="hour"></div>
<div id="minute"></div>
<div id="second"></div>
<div id="start">start</div>
<div id="reset">reset</div>
<div id="pause">pause</div>

JQuery transition animation

This program randomly selects two employees from a json-object Employees array, winnerPos is already defined.
For better user experience I programmed these functions to change pictures one by one. The animation stops when the randomly selected person is shown on the screen.
The slideThrough function will be triggered when the start button is pressed.
function slideThrough() {
counter = 0;
start = true;
clearInterval(picInterval);
picInterval = setInterval(function () {
changePicture();
}, 500);
}
function changePicture() {
if (start) {
if (counter > winnerPos) {
setWinner();
start = false;
killInterval();
} else {
var employee = Employees[counter];
winnerPic.fadeOut(200, function () {
this.src = 'img/' + employee.image;
winnerName.html(employee.name);
$(this).fadeIn(300);
});
counter++;
}
}
}
The problem is the animation doesn't work smoothly. At first it works, but not perfect. The second time the transition happens in an irregular way, i.e. different speed and fadeIn/fadeOut differs from picture to picture.
Could anyone help me to fine-tune the transition?
I would avoid using setInterval() and add a function to the call to .fadeIn() that starts the animation of the next picture.
It would look like this:
function changePicture(pos) {
pos = pos || 0;
if (pos <= winnerPos) {
var employee = Employees[pos];
winnerPic.fadeOut(200, function() {
this.src = 'img/' + employee.image;
winnerName.html(employee.name);
$(this).fadeIn(300, function() {
changePicture(pos + 1);
});
});
} else {
setWinner();
}
}
To start the animation, you call changePicture() without any arguments, like this.
changePicture();
jsfiddle

Reset slide interval JQuery

I've made a slide show width a javascript and Jquery. But I need to reset the slide interval when the user is navigating manualy to the next or previous slide. I am relatively new to javascipt and it's syntax. Any help will be appriciated. Here is my code:
<script type="text/javascript" src="/elements/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var currentSlideId = 0;
var slidesAmount = 0;
function selectSlide(id) {
jQuery(".startpage-test.slide" + id).show().siblings(".startpage-test").hide();
jQuery(".slideshow-show-active.slide" + id).addClass("active").siblings(".slideshow-show-active").removeClass("active");
}
function nextSlide() {
currentSlideId++;
if (currentSlideId >= slidesAmount) currentSlideId = 0;
selectSlide(currentSlideId);
}
function prevSlide() {
currentSlideId--;
if (currentSlideId < 0) currentSlideId = slidesAmount - 1;
selectSlide(currentSlideId);
}
jQuery(document).ready(function() {
slidesAmount = jQuery(".startpage-test").length;
jQuery(".show_previous").click(function() {
prevSlide();
return false;
});
jQuery(".show_next").click(function() {
nextSlide();
return false;
});
window.setInterval(function() {
nextSlide();
}, 7000);
});
jQuery("object.flashContent").each(function () {
swfobject.registerObject(jQuery(this).attr("id"), "9.0.0");
});
</script>
The next-/prev-button looks like this:
<div class="show_next">
<span class="slide_nav"><img src="/elements/next.png" width="57" alt="Next"></span>
</div>
<div class="show_previous">
<span class="slide_nav"><img src="/elements/prev.png" width="57" alt="Previous"></span>
</div>
In all slides there is a link of course, and it would also be nice to stop the slide interval when hovering this a-tag. Unfortunately I don't know how to do this either.
You can assign the result of setInterval() to a variable, then call clearInterval() passing in that variable whenever you need. So in your case, change this code:
window.setInterval(function() {
nextSlide();
},
to this:
var interval = window.setInterval(function() {
nextSlide();
},
Then, in any.hover(), .mouseenter(), .click() or whatever other mouse event handler you are using, simply call:
window.clearInterval(interval);
Of course, you need to reinstate the interval when you want to restart it!

js/jQuery - exit function by mouse position

I have a recursive function for a kind of image slider.
function nextCol(col) {
$('.menubox_col').fadeOut();
$('.menubox_col').eq(col).fadeIn(function(){
col++;
if (col > 3) col = 0;
setTimeout(function(){ nextCol(col) }, 1000);
});
}
<div id="menubox">
<div class="menubox_col">content</div>
<div class="menubox_col">content</div>
<div class="menubox_col">content</div>
<div class="menubox_col">content</div>
</div>
This works fine, but I found no way to stop the recursive function when the mouse cursor enters the #menubox div.
While you could use clearTimeout and then restart the animation again, you could simply set a flag, which means you don't need to stop and start timers... This will stop the animation when the mouse is over the menubox, and continue it when it leaves. I also took the liberty of making some small code changes - I find the result much simpler:
$(function(){
var col = 0, hover = false;
function nextCol() {
if(hover){return;} // if their mouse is over, do nothing
col = (col+1) % 4; // make this a one-liner. the 4 probably shouldn't be hard-coded though, it could be $('.menubox_col').length
$('.menubox_col').fadeOut().eq(col).fadeIn();
}
setInterval(nextCol, 1000);
$('#menubox').hover(function(){ hover=true; }, function(){ hover=false; });
});
You could clear the timeout using clearTimeout:
var timeoutHandle = null;
function nextCol(col) {
$('.menubox_col').fadeOut();
$('.menubox_col').eq(col).fadeIn(function() {
col++;
if (col > 3) { col = 0; }
timeoutHandle = setTimeout(function() {
nextCol(col);
}, 1000);
});
}
$('#menubox div').mouseenter(function() {
window.clearTimeout(timeoutHandle);
});

Categories

Resources