Previous and Next functions for js slider - javascript

I have almost finished this slider, but I don't know how to implement the functionality for next() and prev(). How can I implement these functions?
http://jsfiddle.net/M4t4L/11/
$(function () {
var container = $("#scene"),
i = 0,
count = container.find("li").length,
j = container.find("li").length - 1,
isAnimating = false;
container.find("li:first").css({
"width": "100%"
});
$("#trigger").click(function (e) {
if (!isAnimating) {
isAnimating = true;
e.preventDefault(e);
i++; if (i >= count) { i = 0; }
j++; if (j >= count) { j = 0; }
container.find("li")
.finish()
.removeClass('active')
.last()
.width(0)
.addClass("active")
.animate({
"width": "100%"
}, 800,
function () {
container.find("li").first().appendTo(container);
isAnimating = false;
});
}
});
});
The problem is that when I implement these functions and press the next or prev. Displays the last slide on one second, and then switches to the desired
http://jsfiddle.net/M4t4L/9

If you want to get a Next or Prev function running, you want to take control of the number of the slider where you are. I'm afraid you will have to play around with your i/j and make the position go in both directions.
Right now you count up your i and j, where you might want to go is to have a position var and an array of slider objects, then the click only would have to call for the next/prev object to be loaded and the animation can begin.
Something like this maybe..
var pos = 0;
var container = $('#scene').find('li');
$('.back').click(function() {
pos = pos - 1;
moveIt(pos);
});
$('.forth').click(function() {
pos = pos +1;
moveIt(pos);
});
function moveIt(pos) {
container[pos]... // Your animation goes here
}

Related

Stop loop and fade in area that is hovered on

I have a bit of javascript/jquery I am trying to figure out. What I have already is three boxes that the content fades in and out and loops through the three and repeats. What I am trying to do is when "box x" is hovered over the loop fades out and stops never to start again, and the box that is hovered on, the content below the box fades in and stays... unless another box is hovered over, then the content that faded in from the other hovered box will fade out and the new box that was hovered on, the content that coincides with that box fades in and stays fade in, and so forth.
How would I go about doing this?
Here is a jsfiddle example: http://jsfiddle.net/q0htx0no/
javascript/jquery
var infoboxes = $(".count p");
var counter = 0;
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
rotate();
})
}, 1000);
});
}
$(function() {
rotate();
});
Thanks for any help
One option would be to have a global variable (a 'flag') that would indicate if the rotation should be stopped. Once a box has been hovered over, it should set hovered to True and should fade in that specific box.
Yep, use a global variable. Something like this:
var infoboxes = $(".count p");
var counter = 0;
var goAhead = true;
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
checkRotate();
})
}, 1000);
});
}
function checkRotate() {
if (goAhead) { rotate(); }
}
$('.about').on('mouseover', function() {
goAhead = false;
var index = $(this).index();
var boxesToClear = $(infoboxes).filter(function(i) { return i !== index; });
$(boxesToClear).fadeOut(1000, function() {
$(infoboxes[index]).fadeIn(1000);
});
});
checkRotate();
DEMO
Here's one way to do it. It can probably be improved.
http://jsfiddle.net/vbt67x0h/2/
var infoboxes = $(".count p");
var counter = 0;
var isrotating = false;
function rotate(){
isrotating = true;
$(infoboxes[counter]).fadeIn(1000).delay(1000).fadeOut(1000);
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
}
//immediately stop rotate and hide all
function stoprotate(){
clearInterval(tmrrotate);
isrotating = false;
for(var x=0;x<infoboxes.length;x++){
$(infoboxes[x]).stop();
$(infoboxes[x]).hide();
}
}
rotate();
//rotate every 3 seconds, 1 to fadein, 1 to pause, 1 to fadeout
var tmrrotate = setInterval(function() {
rotate();
}, 3000);
$(".about").on('mouseover', function() {
if(isrotating){stoprotate()}
$(infoboxes[$(this).index()]).fadeIn(1000);
})
.on('mouseleave', function() {
$(infoboxes[$(this).index()]).fadeOut(1000);
});
You should make a timed array:
var arTimer = [];
and push all timers into that array, clearTimeout on hover and show only hovered index:
var infoboxes = $(".count p");
var counter = 0;
var arTimer = [];
function rotate() {
$(infoboxes[counter]).fadeIn(1000, function() {
arTimer.push(setTimeout(function() {
$(infoboxes[counter]).fadeOut(1000, function() {
counter = counter < infoboxes.length - 1 ? counter + 1 : 0;
rotate();
})
}, 1000));
});
}
function cleararTimer(){
for (var i = 0; i < arTimer.length; i++) {
clearTimeout(arTimer[i]);
}
}
$(function() {
rotate();
$('.about').on('mouseover', function(){
cleararTimer();
var hovered = $(this).index();
$('.count p').not(':eq('+hovered+')').fadeOut(1000);
$('.count p:eq('+hovered+')').fadeIn(1000);
});
});
jsFiddle Example

Autostart jQuery slider

I'm using a script that animates on click left or right to the next div. It currently works fine but I'm looking to add two features to it. I need it to repeat back to the first slide if it is clicked passed the last slide and go to the last slide if click back from the first slide. Also, I'm interested in getting this to autostart on page load.
I've tried wrapping the clicks in a function and setting a setTimeout but it didn't seem to work. The animation is currently using CSS.
Here's the current JS:
<script>
jQuery(document).ready(function() {
var boxes = jQuery(".box").get(),
current = 0;
jQuery('.right').click(function () {
if (current == (-boxes.length + 1)){
} else {
current--;
updateBoxes();
}
console.log(-boxes.length + 1);
console.log(current);
});
jQuery('.left').click(function () {
if (current === 0){
} else{
current++;
updateBoxes();
}
});
function updateBoxes() {
for (var i = current; i < (boxes.length + current); i++) {
boxes[i - current].style.left = (i * 100 + 50) + "%";
}
}
});
</script>
Let me know if I need a jsfiddle for a better representation. So far, I think the code is pretty straightforward to animate on click.
Thanks.
Try
jQuery(document).ready(function () {
var boxes = jQuery(".box").get(),
current = 0,
timer;
jQuery('.right').click(function () {
if (current == (-boxes.length + 1)) {
current = 0;
} else {
current--;
}
updateBoxes();
}).click(); //initialize the view
jQuery('.left').click(function () {
if (current === 0) {
current = -boxes.length + 1;
} else {
current++;
}
updateBoxes();
});
function updateBoxes() {
//custom implementation for testing
console.log('show', current)
$(boxes).hide().eq(-current).show();
autoPlay();
}
function autoPlay() {
clearTimeout(timer);
//auto play
timer = setTimeout(function () {
jQuery('.right').click();
}, 2500)
}
});
Demo: Fiddle
Here's an example based on my comment (mostly pseudocode):
$(function(){
var boxes = $('.box'),
current = 0,
timer;
// Handler responsible for animation, either from clicking or Interval
function animation(direction){
if (direction === 1) {
// Set animation properties to animate forward
} else {
// Set animation properties to animate backwards
}
if (current === 0 || current === boxes.length) {
// Adjust for first/last
}
// Handle animation here
}
// Sets/Clears interval
// Useful if you want to reset the timer when a user clicks forward/back (or "pause")
function setAutoSlider(set, duration) {
var dur = duration || 2000;
if (set === 1) {
timer = setInterval(function(){
animation(1);
}, dur);
} else {
clearInterval(timer)
}
}
// Bind click events on arrows
// We use jQuery's event binding to pass the data 0 or 1 to our handler
$('.right').on('click', 1, function(e){animation(e.data)});
$('.left').on('click', 0, function(e){animation(e.data)});
// Kick off animated slider
setAutoSlider(1, 2000);
Have fun! If you have any questions, feel free to ask!

Adding delay to DIV animation

I'm trying to create div boxes step by step and animate them for several times when a button is pressed. I have a running code, and everything is going well. It goes right to the endhost, then it goes left again to its original place. This is mainly what I do, and also the demo is found here: http://jsfiddle.net/54hqm/3/
Now I want to happen after each click, is basically to move each DIV one after another, with a delay, instead of moving the whole stack of DIVs at once. I don't exactly know what to do. Can anyone help me with that?
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
$("button").click(function () {
if (count < 4) {
items = items + 1;
count++;
} else {
items = items * 2;
}
speed = $("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + packetNumber + "</font>").appendTo(div);
packetNumber++;
div.css("left",left+"px");
div.hide();
left += 20;
}
}
function animateDivs() {
$(".t").each(function () {
var packet = $(this);
packet.show();
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
top: '+=20px',
backgroundColor: "#f09090",
text: '12'
}, speed / 4, "swing", function () {
$('.span').fadeOut(100, function () {
$(this).text(function () {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
packet.delay(1000).animate({left:'-=230px'}, speed);
packet.animate({left:'-=230px'}, speed);
}).promise().done(function(){
$(".packets").empty();});
}
});
You can make this with 2 small modifications:
In your each() function, add the index parameter to know the index of the currently animating packet:
$(".t").each(function (index) {
Before your animate calls, insert a packet.delay() with a delay increasing with every item:
packet.delay(index * 250);
I updated your fiddle to show results.
Update: I made a second version based on your comment.

JavaScript how to reverse this animation, after click another link

$('#home').click(doWork);
function doWork() {
var index = 0;
var boxes = $('.box1, .box2, .box3, .box4, .box5, .box6');
function start() {
boxes.eq(index).addClass('animated');
++index;
setTimeout(start, 80);
};
start();
}
when i click a link, this animation start . And after end the animation, i need to reverse this animation, after click another link.
Here's code that allows you to start the process, as well as interrupt it to do the reverse:
(function () {
"use strict";
var doWork,
index,
boxes,
numBoxes,
workerTO;
index = 0;
boxes = $(".box1, .box2, .box3, .box4, .box5, .box6");
numBoxes = boxes.length;
doWork = function (changer, reverse) {
var direction, worker;
clearTimeout(workerTO);
direction = reverse ? -1 : 1;
worker = function () {
if (reverse) {
if (index < 0) {
index = 0;
return;
}
} else {
if (index >= numBoxes) {
index = numBoxes - 1;
return;
}
}
console.log(index);
changer(boxes.eq(index));
index += direction;
workerTO = setTimeout(worker, 80);
};
worker();
};
$("#home").click(function () {
doWork(function (el) {
el.addClass("animated");
});
});
$("#home2").click(function () {
doWork(function (el) {
el.removeClass("animated");
}, true);
});
}());
DEMO: http://jsfiddle.net/NcdZT/1/
I'm sure some things could be condensed and made more efficient (like the if statements), but this seems readable and achieves what you want.
Keeping track of the setTimeout allows the process to be interrupted. If you increased the timeout from 80 to something more noticeable (or if you click fast enough), you would see that the "animation" can be reversed midway through.

.next() not working as intended

So,
if($(this).hasClass('active')){
$(this).removeClass('active');
$(this).prev().addClass('active');
}
works fine, it adds the class "active" to this previous div of the same kind.
if($(this).hasClass('active')){
$(this).removeClass('active');
$(this).next().addClass('active');
}
However, adds the class to the next div (as i intend for it to do) for about 0.5 of a second BUT then removes it.
Here's ALL of the jQuery (as per your comments below) - Please do not comment on my horrible code organization
$(window).load(function () {
// Initial variables
var numberSlides = 0;
var currentSlide = 1;
var ready = true;
var pageWidthR = $(document).width() - 352;
var pageWidthL = $(document).width() - 352;
// Update number of slides by number of .slide elements
$('#features-slider .slide').each(function () {
numberSlides++;
});
// Go through each slide and move it to the left of the screen
var i = 0;
$($('#features-slider .slide').get().reverse()).each(function () {
if (i == 0) {
} else {
var newWidth = i * 115;
$(this).css('left', '-' + newWidth + '%');
}
i++;
});
// Animate the first slide in
$('#features-slider .slide:last-child').addClass('active').animate({
left: 0
}, 1500);
// Remove the loading message
$('#loading').fadeOut(1000, function () {
$('#loading').remove();
// Now that we're done - we can show it
$('#features-slider').show();
});
/***** Left and Right buttons *****/
/* Right */
$('#rightbutton').click(function () {
var numberSlides = 0;
$('#features-slider .slide').each(function () {
numberSlides++;
});
var index = $('.slide.active').index() + 1;
if (!$('.slide').is(':animated') && index != 1) {
$('#features-slider .slide').each(function () {
if ($(this).hasClass('active')) {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) + 115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) + 115;
}
$(this).animate({
left: newLeft + '%'
}, 1500);
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$(this).prev().addClass('active');
}
});
}
});
/* Left */
$('#leftbutton').click(function () {
var numberSlides = 0;
$('#features-slider .slide').each(function () {
numberSlides++;
});
var index = $('.slide.active').index() + 1;
if (!$('.slide').is(':animated') && index != numberSlides) {
$('#features-slider .slide').each(function () {
if ($(this).hasClass('active')) {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) - 115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft) - 115;
}
$(this).animate({
left: newLeft + '%'
}, 1500);
if ($(this).hasClass('active')) {
$(this).next().addClass('active');
$(this).removeClass('active').not($(this).next());
}
});
}
});
});
$(document).ready(function () {
// Hide the slider and show a loading message while we do stuff and the images / DOM loads - Also disable overflow on the body so no horizontal scrollbar is shown
$('body').css('overflow-x', 'hidden');
$('#features-slider').hide();
$('#loading').html('<center> <img id="loader" src="/wp-content/themes/responsive/library/images/ajax-loader.gif" /> Loading</center>');
});
RESOLVED
New left button function :
$('#leftbutton').click(function(){
var numberSlides = 0;
$('#features-slider .slide').each(function(){
numberSlides++;
});
var index = $('.slide.active').index()+1;
if( !$('.slide').is(':animated') && index != numberSlides ){
var done = false;
$('#features-slider .slide').each(function(){
if($(this).hasClass('active')){
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft)-115;
} else {
var currentLeft = $(this).css('left');
var newLeft = parseInt(currentLeft)-115;
}
$(this).animate({left: newLeft+'%'}, 1500);
if($(this).hasClass('active') && done == false){
$(this).next().addClass('active');
$(this).removeClass('active');
done = true;
}
});
});
If you're iterating forward through the elements, then it should be clear what's going on - you add the "active" class to the next element, and then the next iteration takes it away.
This is just a guess however as you did not post enough code for me (or anybody else) to be sure.
edit — ok now that you've updated the question, it's clear that the guess was correct. The .each() function will iterate forward through the elements. When an element has the "active" class, and the code removes it and adds it to the next element, then on the next iteration the work is undone.
Since you are referencing this and by the behavior you're describing, you are likely iterating a loop for a list of elements. As a result, you are completing the action you want but the next iteration is removing the previous changes due to your usage of removing a class and then adding the class back.
As it stands now, your code does not illustrate how this occurence can be happening.
Update:
As suspected, you seem to be looping as signified by: each(function(){. While iterating through your objects the class is being pushed forward and is not acting as desired. You are stating add the class to the next element, but remove it from the current element, and this behavior continues through your iteration.
On a side note, update your code to call removeClass() on the current object first, before adding it to the next object:
if ($(this).hasClass('active')) {
$(this).removeClass('active').next().addClass('active');
}

Categories