ExtJs Animation - Show/Fade elements ad infinitum - javascript

I'm trying to create a never-ending looping animation using ExtJs, but am hitting the obvious barrier - calling a function recursively that potentially never ends tends to fill the stack pretty quickly. My (non-functioning) code is below; this function gets passed an array of strings which correspond to the divs to be shown and hidden. Without the callback, the code produces the desired show/fade effect, but obviously only the once.
// 'divArray' - a string array containing the IDs of the divs to cycle.
function cycleDivs (divArray) {
var len, i, el;
// Sanity check.
if (divArray === null || !Ext.isArray(divArray) || divArray.length === 0) {
return;
}
// Get the length of the array; we'll need this to loop the animation.
len = divArray.length;
for (i = 0; i < len; i++) {
// Get the element.
el = Ext.fly(divArray[i]);
// Sanity check.
if (el) {
el.sequenceFx();
el.fadeIn({
endOpacity: 1,
easing: 'easeOut',
duration: 3
});
el.pause(2)
el.fadeOut({
endOpacity: 0,
easing: 'easeOut',
duration: 3
});
if (i === len - 1) {
// Recursive call if this is the last element in the array.
el.callback = cycleDivs(divArray);
}
}
}
}
Caveat: I've achieved this sort of effect before with jQuery and its wide variety of plugins, but as it's a work project I can only use the library I've got, which is ExtJs.
Thanks in advance for any pointers.

I ended up porting parts of jquery.slideShow by Marcel Eichner, and the SO answer for execute a method on an existing object with window.setInterval for my requirements. Code below for any who might find a use for it. I also now pass the elements to be animated into the constructor, rather than just their IDs.
// Constructor function.
MyNamepsace.Slideshow = function (divArray) {
// Persist the div array.
this.divArray = divArray;
// Internal vars
this.numSlides = this.divArray.length;
this.current = 0;
if (this.current >= this.numSlides) {
this.current = this.numSlides - 1;
}
this.last = false;
this.interval = false;
};
Ext.apply(MyNamespace.Slideshow.prototype, {
// Initialisation method.
init: function() {
this.gotoSlide(this.current);
this.auto();
},
// This is a "toy" version of "bind".
bind: function(object, method) {
return function() {
method.call(object);
};
},
// Set up automatic slideshow.
auto: function() {
this.interval = window.setInterval(this.bind(this, this.next), 3000);
},
// Stop automatic slideshow.
stopAuto: function() {
if (this.interval) {
window.clearInterval(this.interval);
this.interval = false;
}
},
// Go to next slide.
next: function() {
this.gotoSlide(this.current + 1);
},
// Go to specific slide.
gotoSlide: function(index) {
var oldSlide, newSlide;
if (index < 0) {
index = this.numSlides - 1;
}
if (index >= this.numSlides) {
index = 0;
}
if (index === this.current) {
return;
}
// get slide elements
oldSlide = this.divArray[this.current];
newSlide = this.divArray[index];
this.stopAuto();
// Start transition
oldSlide.fadeOut({
easing: 'easeOut',
duration: 3,
callback: this.auto,
useDisplay: true,
scope: this
});
newSlide.fadeIn({
easing: 'easeIn',
duration: 3
});
this.last = this.current;
this.current = index;
}
});

I would do something like :
var cycleDivs = function(divs) {
var i = 0;
var fadeFn = function() {
divs[i].sequenceFx().fadeIn({
...
}).pause(2).fadeOut({
...,
callback : fadeFn
});
i = (i+1)%divs.length;
}
fadeFn();
}
Of course I removed all sanity checks ;)

Related

Hiding and revealing divs

I've a script which works fine when written like this:
var isPaused = false,
jQuery(function () {
var $els = $('div[id^=film]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
if (!isPaused) {
if (len > 1) {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len;
$els.eq(i).fadeIn();
});
}
}
}, 3500);
});
But I wanted to add a next and prev button so I rewrote like this, which I thought would work.
var isPaused = false,
$els = $('div[id^=film]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(Slide(1), 3500);
function Slide (x) {
if (!isPaused) {
if (len > 1) {
$els.eq(i).fadeOut(function () {
i = (i + x) % len;
if (i<0) {
i = len;
}
$els.eq(i).fadeIn();
});
}
}
}
$('#next').click(Slide(1));
$('#prev').click(Slide(-1));
But this code is just displaying all the divs when the page is loaded and then doesn't fade them in and out or allow the next and prev buttons to work. What am I doing wrong?
UPDATE
Perhaps I should ask this differently. Given the first block of code, how should I change it to enable Prev and Next buttons?
You want to do:
$('#next').click(function(){Slide(1);});
$('#prev').click(function(){Slide(-1);});
and
setInterval(function(){Slide(1);}, 3500);
instead, as with your current code, Slide(1) is already being computed, and the click function will just call the value returned from it (as it has no return in the function, this will not be defined)
By wrapping your calls to Slide in a function, this makes the clicks call that function, which in turn calls Slide
You also want to set your index to len - 1 if you go negative, rather than to len, as you're dealing with a zero indexed array:
if (i<0) {
i = len - 1;
}
You jQuery event callbacks must be inside a load structure like:
// Wait for DOM load
$(document).ready(function() {
$('#next').click(function(){ Slide(1); });
$('#prev').click(function(){ Slide(-1); });
});
And I would like to suggest you to change your:
setInterval(Slide(1), 3500);
to
setInterval(function() {
Slide(1);
}, 3500);
Hope it helps

jQuery animation for each element

I do not have much experience in animation on Jquery. I want to make a simple animation that will highlight my text line by line with the possibility of stopping. I know how to do something like this for one line but I have no idea how to deal with loop.
here is my code:
var lines = $('#page')[0].getClientRects();
for (var i=0, max = lines.length; i < max; i++)
{
$('#under_liner')
.queue(function() {
$(this).css('top', lines[i].bottom).dequeue();
})
.animate({
width: lines[i].right - lines[i].left
}, 1000 )
.queue(function() {
$(this).css('width', 0).dequeue();
});
}
and jsfiddle http://jsfiddle.net/mz03kfua/2
I don't know if this is exactly what you are looking for, but here's how I'd do it.
Make a function that does the underlining
Make a recursive call on animation callback
Create a global variable to keep count of the current underlined line
Add a boolean that stops the function when false
var lines = $('#page')[0].getClientRects();
var play = true;
var index = 0;
underlineLine();
$('button').click(function(){
play = !play
if(play){
underlineLine()
$(this).html("STOP")
}else{
$(this).html("CONTINUE")
}
})
function underlineLine(){
if(index >= lines.length) return
if(play){
$('#under_liner').css('top', lines[index].bottom).dequeue();
$('#under_liner').css('width','0px');
$('#under_liner').animate({
width: lines[index].right - lines[index].left
}, 1000, function(){
underlineLine(index++)
})
$('#under_liner').css('width', 0).dequeue();
}
}
HERE IS A FIDDLE WITH THE CODE.
Hope it helps.
http://jsfiddle.net/mz03kfua/4/
var lines = $('#page')[0].getClientRects();
var current = 0;
var element;
function animateLine() {
if(typeof lines[current] !== "object") {
return;
}
var line = lines[current];
element = jQuery("<div />", {"class": "under_liner"}).prependTo("#page");
element.css({top: line.bottom}).animate({width: line.width}, 1000, function() {
current++;
animateLine();
});
}
function stopLine(e) {
e.preventDefault();
element.stop(true);
}
jQuery(".stop").click(stopLine);
animateLine();

Javascript - How do I improve performance when animating integers?

On the site I'm working on, we collect data from a datasource and present these in their own design element, in the form of an SVG. The SVG files are renamed to .php in order to insert the dynamic data from the datasource.
Then, I'm using inview javascript to initialize a function that animates the data from the source, from 0 to their actual value. However, I notice this gets kinda heavy on the browser, when there are a lot of elements that are running the animate function.
Is there perhaps a smarter way of doing this? I haven't really dug that much into it, because it's not that bad. I just happened to notice the lag when scrolling through the area being repainted.
Here's my js code:
$('.inview article').bind('inview', function(event, isInView, visiblePartX, visiblePartY) {
if (isInView) {
// element is now visible in the viewport
if (visiblePartY == 'top' || visiblePartY == 'both' || visiblePartY == 'bottom') {
var $this = $(this);
var element = $($this);
$this.addClass('active');
reinitializeText(element);
$this.unbind('inview');
// top part of element is visible
} else if (visiblePartY == 'bottom') {
} else {
}
} else {
}
});
function reinitializeText(element) {
var svg = element.find('svg');
var children = svg.children('.infographics_svg-text');
// If there is no class in svg file, search other elements for the class
if (children.length == 0) {
var children = element.find('.infographics_svg-text');
}
children.each(function (){
var step = this.textContent/100;
var round = false;
if (this.textContent.indexOf('.') !=-1) {
round = true;
}
animateText(this, 0, step, round);
});
}
function animateText(element, current, step, round) {
if (current > 100) return;
var num = current++ *step;
if (round) {
num = Math.round((num)*100)/100
} else {
num = Math.round(num);
}
element.textContent = num;
setTimeout(function() {
animateText(element, current, step, round);
}, 10);
}
Edit: Because of the difference in data values received from the source (low numbers to huge numbers), The speed of the animation is increased so it doesn't go on forever

Jquery = setInterval code works in Firefox but not in Chrome

The code (from an old plugin that I am trying to make responsive) slides a set of images across every n seconds. It uses setInterval code as below, and works well on Firefox. On Chrome it runs once only, and debugging indicates that the second setInteral function is just not called. Please help as its diving me mad. Running example at http://lelal.com/test/site10/index.html (sorry about the load time)
play = setInterval(function() {
if (!busy) {
busy = true;
updateCurrent(settings.direction);
slide();
}
}, settings.speed);
The complete plugin code is below (sorry its long)
/*
* jQuery Queue Slider v1.0
* http://danielkorte.com
*
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
(function($){
var QueueSlider = function(element, options) {
var play = false,
busy = false,
current = 2,
previous = 2,
widths = [],
slider = $(element),
queue = $('ul.queue', slider),
numImages = $('img', queue).size(),
viewportWidth = slider.width(),
settings = $.extend({}, $.fn.queueSlider.defaults, options);
$(window).resize(function(){
if(busy !== false)
clearTimeout(busy);
busy = setTimeout(resizewindow, 200); //200 is time in miliseconds
});
function resizewindow() {
viewportWidth = slider.width();
if (settings.scale > 0) {
slider.css('height',viewportWidth * settings.scale);
computeQueueWidth();
}
queue.css('left', -getQueuePosition());
busy = false;
}
function requeue() {
$('li', queue).each(function(key, value) {
$(this).attr('class', 'slide-' + (key+1));
});
}
function updateCurrent(dir) {
current += dir;
if (current < 1) {
current = numImages;
} else if (current > numImages) {
current = 1;
}
}
function getQueuePosition() {
var i = 0, index = current-1,
queuePosition = (viewportWidth - widths[index]) / -2;
for (i = 0; i < index; i++) { queuePosition += widths[i]; }
return queuePosition;
}
function computeQueueWidth() {
var queueWidth = 0;
// factor = slider.height() / settings.imageheight;
// settings.imageheight = settings.imageheight * factor;
// Get the image widths and set the queue width to their combined value.
$('li', queue).each(function(key, value) {
var slideimg = $("img", this),
slide = $(this),
// width = slide.width() * factor,
width = slideimg.width();
slide.css('width', width+'px');
queueWidth += widths[key] = width;
});
queue.css('width', queueWidth + 500);
}
function slide() {
var animationSettings = {
duration: settings.transitionSpeed,
queue: false
};
// Emulate an infinte loop:
// Bring the first image to the end.
if (current === numImages) {
var firstImage = $('li.slide-1', queue);
widths.push(widths.shift());
queue.css('left', queue.position().left + firstImage.width()).append(firstImage);
requeue();
current--; previous--;
}
// Bring the last image to the beginning.
else if (current === 1) {
var lastImage = $('li:last-child', queue);
widths.unshift(widths.pop());
queue.css('left', queue.position().left + -lastImage.width()).prepend(lastImage);
requeue();
current = 2; previous = 3;
}
// Fade in the current and out the previous images.
if (settings.fade !== -1) {
$('li.slide-'+current, queue).animate({opacity: 1}, animationSettings);
$('li.slide-'+previous, queue).animate({opacity: settings.fade}, animationSettings);
}
// Animate the queue.
animationSettings.complete = function() { busy = false; };
queue.animate({ left: -getQueuePosition() }, animationSettings);
previous = current;
}
//
// Setup the QueueSlider!
//
if (numImages > 2) {
// Move the last slide to the beginning of the queue so there is an image
// on both sides of the current image.
if (settings.scale > 0) {
slider.css('height',viewportWidth * settings.scale);
}
computeQueueWidth();
widths.unshift(widths.pop());
queue.css('left', -getQueuePosition()).prepend($('li:last-child', queue));
requeue();
// Fade out the images we aren't viewing.
if (settings.fade !== -1) { $('li', queue).not('.slide-2').css('opacity', settings.fade); }
// Include the buttons if enabled and assign a click event to them.
if (settings.buttons) {
slider.append('<button class="previous" rel="-1">' + settings.previous + '</button><button class="next" rel="1">' + settings.next + '</button>');
$('button', slider).click(function() {
if (!busy) {
busy = true;
updateCurrent(parseInt($(this).attr('rel'), 10));
clearInterval(play);
slide();
}
return false;
});
}
// Start the slideshow if it is enabled.
if (settings.speed !== 0) {
play = setInterval(function() {
if (!busy) {
busy = true;
updateCurrent(settings.direction);
slide();
}
}, settings.speed);
}
}
else {
// There isn't enough images for the QueueSlider!
// Let's disable the required CSS and show all one or two images ;)
slider.removeClass('queueslider');
}
};
$.fn.queueSlider = function(options) {
return this.each(function(key, value) {
var element = $(this);
// Return early if this element already has a plugin instance.
if (element.data('queueslider')) { return element.data('queueslider'); }
// Pass options to plugin constructor.
var queueslider = new QueueSlider(this, options);
// Store plugin object in this element's data.
element.data('queueslider', queueslider);
});
};
$.fn.queueSlider.defaults = {
scale: 0,
imageheight: 500,
fade: 0.3, // Opacity of images not being viewed, use -1 to disable
transitionSpeed: 700, // in milliseconds, speed for fade and slide motion
speed: 7000, // in milliseconds, use 0 to disable slideshow
direction: 1, // 1 for images to slide to the left, -1 to silde to the right during slideshow
buttons: true, // Display Previous/Next buttons
previous: 'Previous', // Previous button text
next: 'Next' // Next button text
};
}(jQuery));
Have a look here:
http://www.w3schools.com/jsref/met_win_setinterval.asp
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
Looks like you're calling clearInterval after the first usage of play, which makes it stop working.

javascript 'over-clicking' bug

I have a bug in Javascript where I am animating the margin left property of a parent container to show its child divs in a sort of next/previous fashion. Problem is if clicking 'next' at a high frequency the if statement seems to be ignored (i.e. only works if click, wait for animation, then click again) :
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
//roll margin back to 0
}
An example can be seen on jsFiddle - http://jsfiddle.net/ZQg5V/
Any help would be appreciated.
Try the below code which will basically check if the container is being animated just return from the function.
Working demo
$next.click(function (e) {
e.preventDefault();
if($contain.is(":animated")){
return;
}
var marLeft = $contain.css('margin-left'),
$this = $(this);
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
$contain.animate({
marginLeft: 0
}, function () {
$back.fadeOut('fast');
});
} else {
$back.fadeIn(function () {
$contain.animate({
marginLeft: "-=" + regWidth + "px"
});
});
}
if (marLeft > -combinedWidth) {
$contain.animate({
marginLeft: 0
});
}
});
Sometimes is better if you create a function to take care of the animation, instead of writting animation code on every event handler (next, back). Also, users won't have to wait for the animation to finish in order to go the nth page/box.
Maybe this will help you:
if (jQuery) {
var $next = $(".next"),
$back = $(".back"),
$box = $(".box"),
regWidth = $box.width(),
$contain = $(".wrap")
len = $box.length;
var combinedWidth = regWidth*len;
$contain.width(combinedWidth);
var currentBox = 0; // Keeps track of current box
var goTo = function(n) {
$contain.animate({
marginLeft: -n*regWidth
}, {
queue: false, // We don't want animations to queue
duration: 600
});
if (n == 0) $back.fadeOut('fast');
else $back.fadeIn('fast');
currentBox = n;
};
$next.click(function(e) {
e.preventDefault();
var go = currentBox + 1;
if (go >= len) go = 0; // Index based, instead of margin based...
goTo(go);
});
$back.click(function(e) {
e.preventDefault();
var go = currentBox - 1;
if (go <= 0) go = 0; //In case back is pressed while fading...
goTo(go);
});
}
Here's an updated version of your jsFiddle: http://jsfiddle.net/victmo/ZQg5V/5/
Cheers!
Use a variable to track if the animation is taking place. Pseudocode:
var animating = false;
function myAnimation() {
if (animating) return;
animating = true;
$(this).animate({what:'ever'}, function() {
animating = false;
});
}
Crude, but it should give you the idea.
Edit: Your current code works fine for me as well, even if I jam out on the button. On firefox.

Categories

Resources