How to do something everytime .animate repetition ends - javascript

var track = Ti.UI.createView({
width: 100, height: 30,
backgroundColor: '#e8e8e8',
top: '30%'
});
var progress = Ti.UI.createView({
left: 0,
width: 1, height: 30,
backgroundColor: '#00c36a'
});
track.add(progress);
Ti.UI.currentWindow.add(track);
Ti.UI.currentWindow.addEventListener('open', function () {
progress.animate({
width: 100,
duration: 10000,
repeat: 6
});
I have made a custom progress bar using two views and .animate function. How do I do implement some functionality everytime a repetition of progress.animate() is completed

Here is an example of JQuery animation Complete callback.
var cbFunction = function(){
//Animation Complete Callback function
alert('animation completed!');
}
//Test buntton click event
$(".testbutton").on('click',function(){
//Launch animation
$(".test").animate({width:100},1000,cbFunction);
});
.test{
background-color:#ff0000;
width:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="testbutton">TEST</button>
<div class="test">-</div>

Try this:
var repeat = 6;
var rep = 0;
var autoProgress = function() {
createAnimation(progress, function() {
alert('complete nÂȘ-> ' + rep);
rep++;
if (rep < repeat) {
autoProgress();
}
});
};
/**
* create animation to view
* #param Ti.UI.View view
* #param {Function} callback
*/
var createAnimation = function(view, callback) {
callback = _.isFunction(callback) ? callback : function() {
};
//create animate
var animate = Titanium.UI.createAnimation({
width : 100,
duration : 10000,
});
/**
* Fired when the animation complete.
*/
animate.addEventListener('complete', function() {
view.width = 0;
callback();
});
view.animate(animate);
};
Ti.UI.currentWindow.addEventListener('open', autoProgress);

Related

How to create progress bar for Owl Carousel 2?

Official older link for Owl 1 progress bar doesn't even work anymore but I have found working example but also for Owl 1.
I have tried to use the code but I am not able to set it to work with Owl 2
http://codepen.io/anon/pen/GrgEaG
$(document).ready(function() {
var time = 7; // time in seconds
var $progressBar,
$bar,
$elem,
isPause,
tick,
percentTime;
//Init the carousel
$("#owl-demo").owlCarousel({
items: 1,
initialized : progressBar,
translate : moved,
drag : pauseOnDragging
});
//Init progressBar where elem is $("#owl-demo")
function progressBar(elem){
$elem = elem;
//build progress bar elements
buildProgressBar();
//start counting
start();
}
//create div#progressBar and div#bar then prepend to $("#owl-demo")
function buildProgressBar(){
$progressBar = $("<div>",{
id:"progressBar"
});
$bar = $("<div>",{
id:"bar"
});
$progressBar.append($bar).prependTo($elem);
}
function start() {
//reset timer
percentTime = 0;
isPause = false;
//run interval every 0.01 second
tick = setInterval(interval, 10);
};
function interval() {
if(isPause === false){
percentTime += 1 / time;
$bar.css({
width: percentTime+"%"
});
//if percentTime is equal or greater than 100
if(percentTime >= 100){
//slide to next item
$elem.trigger('owl.next')
}
}
}
//pause while dragging
function pauseOnDragging(){
isPause = true;
}
//moved callback
function moved(){
//clear interval
clearTimeout(tick);
//start again
start();
}
//uncomment this to make pause on mouseover
// $elem.on('mouseover',function(){
// isPause = true;
// })
// $elem.on('mouseout',function(){
// isPause = false;
// })
});
#bar{
width: 0%;
max-width: 100%;
height: 4px;
background: #7fc242;
}
#progressBar{
width: 100%;
background: #EDEDED;
}
the callback functions are not being fired because you're calling them on events that don't exist in owlCarousel 2. The events are prefixed with 'on'.
So if you call them like this:
$("#owl-demo").owlCarousel({
items: 1,
onInitialized : progressBar,
onTranslate : moved,
onDrag : pauseOnDragging
});
The functions will be called. Check the owlCarousel event docs here.
Check out this CodePen for an example progressbar in OwlCarousel using CSS transitions.
After running into the need for a progress bar I stumbled across this question, as well as the example of a progress bar with owl-carousel v1.
Using v2.3.3 I came up with the following js/css-animation based solution:
javascript:
const $slider = $('.my-slider')
const SLIDER_TIMEOUT = 10000
$slider.owlCarousel({
items: 1,
nav: false,
dots: false,
autoplay: true,
autoplayTimeout: SLIDER_TIMEOUT,
autoplayHoverPause: true,
loop: true,
onInitialized: ({target}) => {
const animationStyle = `-webkit-animation-duration:${SLIDER_TIMEOUT}ms;animation-duration:${SLIDER_TIMEOUT}ms`
const progressBar = $(
`<div class="slider-progress-bar"><span class="progress" style="${animationStyle}"></span></div>`
)
$(target).append(progressBar)
},
onChanged: ({type, target}) => {
if (type === 'changed') {
const $progressBar = $(target).find('.slider-progress-bar')
const clonedProgressBar = $progressBar.clone(true)
$progressBar.remove()
$(target).append(clonedProgressBar)
}
}
})
scss
.slider-progress-bar {
/* your progress bar styles here */
.progress {
height: 4px;
background: red;
animation: sliderProgressBar ease;
}
}
.my-slider:hover {
.slider-progress-bar .progress {
animation-play-state: paused;
}
}
#keyframes sliderProgressBar {
0% {
width: 0%;
}
100% {
width: 100%;
}
}

jquery plugin, settimeout and div not being append, simple weird case

I'm writing a jquery plugin the code below is not working (I mean the setTimeout is working but nothing is append)
var self = this;
for (var i=0; i<=10; i++) {
setTimeout(function() {
self.append(bubble);
}, 1000);
}
And the code below is working:
for (var i=0; i<=10; i++) {
this.append(bubble);
}
this is a jquery selection. I really don't get what's going on. It can't be scope issue .. can it be ? I don't get it. Thanks in advance for you help
Edit: bubble is a simple div (" ")
Below the whole plugin code:
(function($) {
'use strict';
$.fn.randomBubble = function(options) {
var self = this;
var settings = $.extend({
color: 'blue',
backgroundColor: 'white',
maxBubbleSize: 100
}, options);
var frame = {
height: this.height(),
width: this.width(),
}
var bubble = "<div class='randomBubble'> </div>";
this.getLeft = function(width) {
var left = Math.random() * frame.width;
if (left > (frame.width / 2)) {
left -= width;
} else {
left += width;
}
return left
}
this.getTop = function(height) {
var top = Math.random() * frame.height;
if (top > (frame.height / 2)) {
top -= height;
} else {
top += height;
}
return top
}
this.removeBubbles = function() {
var currentBubbles = this.find('.randomBubble');
if (currentBubbles.length) {
currentBubbles.remove();
}
}
window.oh = this;
for (var i = 0; i <= 10; i++) {
var timer = Math.random() * 1000;
setTimeout(function() {
window.uh = self;
self.append(bubble);
console.log("oh");
}, 1000);
}
this.randomize = function() {
//self.removeBubbles();
var allBubbles = this.find('.randomBubble');
allBubbles.each(function(i, el) {
var height = Math.random() * settings.maxBubbleSize;
var width = height;
$(el).css({
color: settings.color,
backgroundColor: settings.backgroundColor,
zIndex: 1000,
position: 'absolute',
borderRadius: '50%',
top: self.getTop(height),
left: self.getLeft(width),
height: height,
width: width
});
});
}
this.randomize();
//var run = setInterval(self.randomize, 4000);
return this.find('.randomBubble');
}
})(jQuery);
Because the bubbles are appended later due to the setTimeout(), this selector in your randomize() function comes up empty:
var allBubbles = this.find('.randomBubble');
That is why appending them in a simple for loop works fine.
If you really want to use the setTimout() to append your bubbles, one option is to style them when you add them:
setTimeout(function() {
var height = Math.random() * settings.maxBubbleSize;
var width = height;
var b = $(bubble).css({
color: settings.color,
backgroundColor: settings.backgroundColor,
zIndex: 1000,
position: 'absolute',
borderRadius: '50%',
top: self.getTop(height),
left: self.getLeft(width) ,
height: height,
width: width
});
self.append(b);
}, 1000);
Fiddle
Is it because you still call randomize() right away, even when you postpone the creation for one second?
You will also return an empty selection in that case, for the same reason.
Also, you probably want to use the timer variable in setTimeout() instead of hardcoding all to 1000 ms?
this is a javascript selection, the selector in jquery is $(this)
$.fn.randomBubble = function(options) {
var self = $(this);
};

How could I progress the sprite animation on scroll?

I am newbie. I can't sprite animation using jquery..
What's the problem?
How can make progressing the sprite animation on the spot loop as scroll??
$(window).scroll('scroll',function(e){
parallaxScroll();
});
function parallaxScroll() {
var ani_data = [0, -120, -240, -480];
var frame_index = 0;
if ( ScrollCount == 3 ) {
ScrollCount = 1;
$('#fatherwalk').css('background-position', ani_data[frame_index] + 'px 0px');
frame_index++;
if ( frame_index >= ani_data.length ) {
frame_index = 0;
}
}
scrollcount++;
}
Why you don't get a shortcut and try SpinJS?
http://fgnass.github.io/spin.js/
It's so easy to implement and works fine.
Here is a Sample that I've made on JSFiddle
Below a quick implementation of the JS:
$.fn.spin = function (opts) {
this.each(function () {
var $this = $(this),
spinner = $this.data('spinner');
if (spinner) spinner.stop();
if (opts !== false) {
opts = $.extend({
color: $this.css('color')
}, opts);
spinner = new Spinner(opts).spin(this);
$this.data('spinner', spinner);
}
});
return this;
};
$(function () {
$(".spinner-link").click(function (e) {
e.preventDefault();
$(this).hide();
var opts = {
lines: 12, // The number of lines to draw
length: 7, // The length of each line
width: 5, // The line thickness
radius: 10, // The radius of the inner circle
color: '#fff', // #rbg or #rrggbb
speed: 1, // Rounds per second
trail: 66, // Afterglow percentage
shadow: true // Whether to render a shadow
};
$("#spin").show().spin(opts);
});
});
Hope this helps.

Javascript plugin only firing once

I've built a very basic jQuery plugin that essentially positions a sprite image left by a set amount every x milliseconds to create an animation effect. The plugin at this stage is very basic and only has a few options, and it works pretty well.
Apart from that fact that it only fires once! I have multiple instance of the animation on one page and they all fire, but only ever once each.
Now I'm not expert on Javascript and only just managed to cobble this together but here's the code anyhow:
// Animation Plugin
(function($){
$.fn.anime = function(customOptions) {
// Default Options
var defaultOptions = {
slideWidth : 100,
frames : 10,
speed : 40,
minCycles : 1,
stopFrame : 0
};
// Set options to default
var options = defaultOptions;
// Merge custom options with defaults using the setOptions func
setOptions(customOptions);
// Merge current options with the custom option
function setOptions(customOptions) {
options = $.extend(options, customOptions);
};
return this.each(function() {
// Initialize the animation object
var $elem = $('img', this);
var frameCount = 0;
var currentSlideWidth = options.slideWidth;
var intervalID = null;
var cycleCount = 1;
var animate = function() {
if (frameCount < (options.frames -1)) {
$elem.css('left', '-' + currentSlideWidth + 'px');
frameCount++;
currentSlideWidth += options.slideWidth;
}
else {
if (cycleCount < options.minCycles)
{
frameCount = 0;
currentSlideWidth = options.slideWidth;
$elem.css('left', '-' + currentSlideWidth + 'px');
cycleCount++;
}
else
{
window.clearInterval(intervalID);
$elem.css('left', '0px');
}
}
cycleCount = 1;
};
$(this).bind('mouseover', function(){
var intervalID = window.setInterval(animate, options.speed);
});
});
};
})(jQuery);
The code used to call the actual plugin on a dom element is:
$('#animeBolt').anime({
frames: 50,
slideWidth: 62,
minCycles: 1,
speed: 30,
});
This is the html it is called on:
<div class="anime" id="animeBolt">
<img src="_assets/img/anime-bolt.png" alt="Lightning Bolt" width="3100" height="114">
</div>
And finally the css:
.anime {
position: absolute;
overflow: hidden; }
.anime img {
position: absolute;
left: 0;
top: 0; }
#animeBolt {
top: 2669px;
left: 634px;
width: 62px;
height: 116px; }
How do I get the plugin to fire repeatedly?
I've created and modified jsfiddle example using your code. It's working http://jsfiddle.net/9Yz9j/16/
I've change a couple of things:
added clearInterval on mouseover to preven multiple overlapping intervals
moved intervalID variable to outside of each function, and removed var keyword from mousover handler so the script will remember intervalID set on last mouseover
reseting the frameCount, cycleCount and currentSlideWidth variables on animation end (that was actually a clue thing to get animation going more than just once)
Hope that helps

Javascript slider pause function on hover

Looking for a little help with this slider that came with a Magento Template I purchased.
I'm trying to add a pause on hover and resume on mouse out but am very new to getting my hands this dirty with the JavaScript.
Hoping for a push in the right direction
Here is the code I'm working with
function decorateSlideshow() {
var $$li = $$('#slideshow ul li');
if ($$li.length > 0) {
// reset UL's width
var ul = $$('#slideshow ul')[0];
var w = 0;
$$li.each(function(li) {
w += li.getWidth();
});
ul.setStyle({'width':w+'px'});
// private variables
var previous = $$('#slideshow a.previous')[0];
var next = $$('#slideshow a.next')[0];
var num = 1;
var width = ul.down().getWidth() * num;
var slidePeriod = 3; // seconds
var manualSliding = false;
// next slide
function nextSlide() {
new Effect.Move(ul, {
x: -width,
mode: 'relative',
queue: 'end',
duration: 1.0,
//transition: Effect.Transitions.sinoidal,
afterFinish: function() {
for (var i = 0; i < num; i++)
ul.insert({ bottom: ul.down() });
ul.setStyle('left:0');
}
});
}
// previous slide
function previousSlide() {
new Effect.Move(ul, {
x: width,
mode: 'relative',
queue: 'end',
duration: 1.0,
//transition: Effect.Transitions.sinoidal,
beforeSetup: function() {
for (var i = 0; i < num; i++)
ul.insert({ top: ul.down('li:last-child') });
ul.setStyle({'position': 'relative', 'left': -width+'px'});
}
});
}
function startSliding() {
sliding = true;
}
function stopSliding() {
sliding = false;
}
// bind next button's onlick event
next.observe('click', function(event) {
Event.stop(event);
manualSliding = true;
nextSlide();
});
// bind previous button's onclick event
previous.observe('click', function(event) {
Event.stop(event);
manualSliding = true;
previousSlide();
});
// auto run slideshow
new PeriodicalExecuter(function() {
if (!manualSliding) nextSlide();
manualSliding = false;
}, slidePeriod);
}
Now I'm guessing the best way would be to manipulate a hover or mouseover observer similar to the next and previous ones to stop and start but I'm just not sure on how to set this up.
Would appreciate a push in the right direction!
Edit ....
So I'm getting much closer but I seem to have a problem yet hopefully someone who know about prototype can help.
I got it to work by adding this variable
var stopSliding = false;
and then adding an if like so
function nextSlide() {
if (!stopSliding) {
new Effect.Move(ul, {
x: -width,
mode: 'relative',
queue: 'end',
duration: 1.0,
//transition: Effect.Transitions.sinoidal,
afterFinish: function() {
for (var i = 0; i < num; i++)
ul.insert({ bottom: ul.down() });
ul.setStyle('left:0');
}
});
}
}
// previous slide
function previousSlide() {
if (!stopSliding) {
new Effect.Move(ul, {
x: width,
mode: 'relative',
queue: 'end',
duration: 1.0,
//transition: Effect.Transitions.sinoidal,
beforeSetup: function() {
for (var i = 0; i < num; i++)
ul.insert({ top: ul.down('li:last-child') });
ul.setStyle({'position': 'relative', 'left': -width+'px'});
}
});
}
}
then
ul.observe('mouseover', function(event) {
stopSliding = true;
});
ul.observe('mouseout', function(event) {
stopSliding = false;
});
This method works but only Safari will auto start my slideshow now and firefox needs interaction to trigger a start.
However I did find that switching the var to true at the start and switching around the order of the mouseovers it then auto starts fine in Firefox and not in Safari.
Had enough for this evening.
So I managed to get it to work in both Firefox, Safari, IE etc using:
Event.observe( window, 'load', function() { stopSliding = false; });
This ensures that my variable "stopSliding" is set.

Categories