Best way to fade and loop through a set of divs - javascript

Let's say I have the following divs:
<div class="a">You are funny.</div>
<div class="b">You are smart.</div>
<div class="c">You are cool.</div>
What is the best way to show div.a for 5 seconds, then fade out and fade in div.b for 5 seconds and then to div.c and then back to div.a and continue looping for an infinite amount of time?
Thanks :)

You can use an array of values and loop thru them.
var div = $('div').hide(),
news = ['news1', 'news2', 'news3'],
count = 0;
function changeNews() {
div.fadeIn().delay(500).fadeOut(function() {
changeNews();
}).text(news[count++])
if (count == news.length) {
count = 0;
}
}
changeNews();
Check working example at http://jsfiddle.net/qJa3h/

How about a jQuery plugin? I haven't tested it but something like this should get you started:
(function($) {
$.fn.keepFadingToNext = function(options) {
var defaults = {
duration: 5000
};
var settings = $.extend({}, defaults, options);
var original = this;
var doAnimations = function(element) {
element.fadeIn(settings.duration, function() {
element.fadeOut(settings.duration, function() {
var next = element.next();
if (next.length === 0) {
next = original;
}
doAnimations(next);
});
});
};
doAnimations(original);
return original;
};
})(jQuery)
$('.a').keepFadingToNext();
// or
$('.a').keepFadingToNext({ duration: 3000 });

Related

clearinterval() outside of jquery plugin

I create plugin something like this
timer plugin
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.getTimer();
}, 1000);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
and I call the plugin like this.
$(".myTimer").timer({
seconds : 100
});
i called the plugin at timerpage.php. When i changed the page to xxx.php by clicking another menu, the timer interval is still running and i need to the clear the timer interval.
i created a webpage using jquery ajax load. so my page was not refreshing when i change to another menu.
my question is, how to clear the timer interval or destroy the plugin when i click another menu?
Please try with following modifications:
timer plugin:
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
var seconds = options.seconds;
var $this = $(this);
var timerIntval;
var Timer = {
setTimer : function() {
clearInterval(timerIntval);
if(seconds <= 0) {
alert("timeout");
}else {
timerIntval = setInterval(function(){
return Timer.setTimer();
}, 1000);
$this.data("timerIntvalReference", timerIntval); //saving the timer reference for future use
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
Now in some other JS code which is going to change the div content
var intervalRef = $(".myTimer").data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef); //clear the old interval reference
//code to change the div content on menu change
For clearing timer associated with multiple DOM element, you may check below code:
//iterate ovel all timer element:
$("h3[class^=timer]").each(function(){
var intervalRef = $(this).data("timerIntvalReference"); //grab the interval reference
clearInterval(intervalRef);
});
Hope this will give an idea to deal with this situation.
Instead of var timerIntval; set the variable timerInterval on the window object, then you will have the access this variable until the next refresh.
window.timerIntval = setInterval(function() {
Then when the user clicks on any item menu you can clear it:
$('menu a').click(function() {
clearInterval(window.timerIntval);
});
Live example (with multiple intervals)
$('menu a').click(function(e) {
e.preventDefault();
console.log(window.intervals);
for (var i = 0; i < window.intervals.length; i++) {
clearInterval(window.intervals[i]);
}
});
(function($) {
$.fn.timer = function(options) {
var defaults = {
seconds: 60
};
var options = $.extend(defaults, options);
return this.each(function() {
if (!window.intervals) {
window.intervals = [];
}
var intervalId = -1;
var seconds = options.seconds;
var $this = $(this);
var Timer = {
setTimer : function() {
clearInterval(intervalId);
if(seconds <= 0) {
alert("timeout");
} else {
intervalId = setInterval(function(){
//Timer.getTimer();
return Timer.getTimer();
}, 1000);
window.intervals.push(intervalId);
}
},
getTimer : function () {
if (seconds <= 0) {
$this.html("0");
} else {
seconds--;
$this.html(seconds);
}
}
}
Timer.setTimer();
});
};
})(jQuery);
$(".myTimer").timer({
seconds : 100
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<menu>
Menu 1
</menu>
<div class="myTimer"></div>
<div class="myTimer"></div>
Just notice that it's little bit risky because you can only run it once otherwise the interval id of the second will override the first.

Delay inside for loop not working

I want to make a delay inside my for loop, but it won't really work.
I've already tried my ways that are on stackoverflow, but just none of them work for what I want.
This is what I've got right now:
var iframeTimeout;
var _length = $scope.iframes.src.length;
for (var i = 0; i < _length; i++) {
// create a closure to preserve the value of "i"
(function (i) {
$scope.iframeVideo = false;
$scope.iframes.current = $scope.iframes.src[i];
$timeout(function () {
if ((i + 1) == $scope.iframes.src.length) {
$interval.cancel(iframeInterval);
/*Change to the right animation class*/
$rootScope.classess = {
pageClass: 'nextSlide'
}
currentId++;
/*More information about resetLoop at the function itself*/
resetLoop();
} else {
i++;
$scope.iframes.current = $scope.iframes.src[i];
}
}, $scope.iframes.durationValue[i]);
}(i));
}
alert("done");
This is what I want:
First of all I got an object that holds src, duration and durationValue.
I want to play both video's that I have in my object.
I check how many video's I've got
I make iframeVideo visible (ngHide)
I insert the right <iframe> tag into my div container
It starts the $timeout with the right duration value
If that's done, do the same if there is another video. When it was the last video it should fire some code.
I hope it's all clear.
I've also tried this:
var iframeInterval;
var i = 0;
$scope.iframeVideo = false;
$scope.iframes.current = $scope.iframes.src[i];
iframeInterval = $interval(function () {
if ((i + 1) == $scope.iframes.src.length) {
$interval.cancel(iframeInterval);
/*Change to the right animation class*/
$rootScope.classess = {
pageClass: 'nextSlide'
}
currentId++;
/*More information about resetLoop at the function itself*/
resetLoop();
} else {
i++;
$scope.iframes.current = $scope.iframes.src[i];
}
}, $scope.iframes.durationValue[i])
Each $timeout returns a different promise. To properly cancel them, you need to save everyone of them.
This example schedules several subsequent actions starting at time zero.
var vm = $scope;
vm.playList = []
vm.playList.push({name:"video1", duration:1200});
vm.playList.push({name:"video2", duration:1300});
vm.playList.push({name:"video3", duration:1400});
vm.playList.push({name:"video4", duration:1500});
vm.watchingList=[];
var timeoutPromiseList = [];
vm.isPlaying = false;
vm.start = function() {
console.log("start");
//ignore if already playing
if (vm.isPlaying) return;
//otherwise
vm.isPlaying = true;
var time = 0;
for (var i = 0; i < vm.playList.length; i++) {
//IIFE closure
(function (i,time) {
console.log(time);
var item = vm.playList[i];
var p = $timeout(function(){playItem(item)}, time);
//push each promise to list
timeoutPromiseList.push(p);
})(i,time);
time += vm.playList[i].duration;
}
console.log(time);
var lastPromise = $timeout(function(){vm.stop()}, time);
//push last promise
timeoutPromiseList.push(lastPromise);
};
Then to stop, cancel all of the $timeout promises.
vm.stop = function() {
console.log("stop");
for (i=0; i<timeoutPromiseList.length; i++) {
$timeout.cancel(timeoutPromiseList[i]);
}
timeoutPromiseList = [];
vm.isPlaying = false;
};
The DEMO on PLNKR.
$timeout returns promise. You can built a recursive chain of promises like this, so every next video will play after a small amount of time.

Dots for Children in div. A jQuery headache - PART 2

So this is part 2 of my previous question (was advised to start a new question for this one).Just for reference here is my previous post: Dots for Children in div. A jQuery headache
My question now is: How does one go about adding an "active" class/id to the "imgdots" div for styling purposes?For example:Say I'm on image 4 then I want the 4th "imgdots" div to be another colour.Again, any help would be much appreciated! EDITI have set up a fiddle containing what I have thus far. The initial image slider was from a tutorial I followed and kinda pieced it all together from there. Here is the link: jsfiddle.net/Reinhardt/cgt5M/8/
Have you seen nth child css?
http://www.w3schools.com/cssref/sel_nth-child.asp
#showContainer:nth-child(4)
{
background:#ff0000;
}
Try
/* The jQuery plugin */
(function ($) {
$.fn.simpleShow = function (settings) {
var config = {
'tranTimer': 5000,
'tranSpeed': 'normal'
};
if (settings) $.extend(config, settings);
this.each(function () {
var $wrapper = $(this),
$ct = $wrapper.find('.showContainer'),
$views = $ct.children();
var viewCount = $views.length;
var $imgdotholder = $('<div class="imgdotholder"></div>').appendTo('.wrapper');
for (var i = 0; i < viewCount; i++) {
$('<div class="imgdots"></div>').appendTo($imgdotholder);
}
var $imgdots = $imgdotholder.children();
var timer, current = 0;
function loop() {
timer = setInterval(next, config.tranTimer);
}
function next(idx) {
$views.eq(current).hide();
current = idx == undefined ? current + 1 : idx;
if (isNaN(current) || current < 0 || current >= viewCount) {
current = 0;
}
$views.eq(current).fadeIn(config.tranSpeed);
$imgdots.removeClass('current').eq(current).addClass('current');
}
$imgdots.click(function(){
clearInterval(timer);
next($(this).index());
})
$wrapper.find('.btn_nxt').click(function(){
clearInterval(timer);
next();
});
$ct.hover(function(){
clearInterval(timer);
}, loop);
$views.slice(1).hide();
$imgdots.eq(0).addClass('current');
loop();
});
return this;
};
})(jQuery);
/* Calling The jQuery plugin */
$(document).ready(function () {
/**/
$(".wrapper").simpleShow({
'tranTimer': 3000,
'tranSpeed': 800
});
});
Demo: Fiddle

How do I update the html displayed for each iteration of a for loop in javascript / jquery?

How would I have the h1 change for each iteration of the loop? This code now only displays the h1 text after everything is done.
for (i=0; i<array.length; i++) {
$("body > h1").text("Processing #" + i);
// things that take a while to do
}
Additional info: if I resize the window as it loops, the html updates.
var array = ['one', 'two', 'three']
var i = 0;
var refreshIntervalId = setInterval(function() {
length = array.length;
if (i < (array.length +1)) {
$("h1").text("Processing #" + i);
} else {
clearInterval(refreshIntervalId);
}
i++
}, 1000);
http://jsfiddle.net/3fj9E/
Use a setInterval with a one-millisecond delay:
var i=0, j=array.length;
var iv = setInterval(function() {
$("h1").text("Processing #" + i);
// things that take a while to do
if (++i>=j) clearInterval(iv);
}, 1);
http://jsfiddle.net/mblase75/sP9p7/
Sometimes you can force a render by forcing a recalculation of layout
for (i=0; i<array.length; i++) {
$("body > h1").text("Processing #" + i)
.width(); // force browser to recalculate layout
// things that take a while to do
}
It might not work in all browsers.
A better way, that does not block the browser so much:
function doThings(array) {
var queueWork,
i = -1,
work = function () {
// do work for array[i]
// ...
queueWork();
};
queueWork = function () {
if (++i < array.length) {
$("body > h1").text("Processing #" + i);
setTimeout(work, 0); // yield to browser
}
};
}
doThings(yourArray);
DEMO
I've spent a bit of time working out a jquery function that seems to solve this. Basically, it's a process handler that you can add any number of processes to and then call run to sequentially call these in a asynchronous way.
$.fn.LongProcess = function () {
var _this = this;
this.notifications = [];
this.actions = [];
this.add = function (_notification, _action) {
this.notifications.push(_notification);
this.actions.push(_action);
};
this.run = function () {
if (!_this.actions && !_this.notifications) {
return "Empty";
}
//******************************************************************
//This section makes the actions lag one step behind the notifications.
var notification = null;
if (_this.notifications.length > 0) notification = _this.notifications.shift();
var action = null;
if ((_this.actions.length >= _this.notifications.length + 2) || (_this.actions.length > 0 && _this.notifications.length == 0))
action = _this.actions.shift();
//****************************************************************
if (!action && !notification) {
return "Completed";
}
if (action) action();
if (notification) notification();
setTimeout(_this.run, 1000);
//setTimeout(_this.run,1); //set to 1 after you've entered your actual long running process. The 1000 is there to just show the delay.
}
return this;
};
How to use with <h1 class="processStatus"></h1>:
$(function () {
var process = $().LongProcess();
//process.add(notification function, action function);
process.add(function () {
$(".processStatus").text("process1");
}, function () {
//..long process stuff
alert("long process 1");
});
process.add(function () {
$(".processStatus").text("process2");
}, function () {
//..long process stuff
alert("long process 2");
});
process.add(function () {
$(".processStatus").text("process3");
}, function () {
//..long process stuff
alert("long process 3");
});
process.run();
});
if the process is very long you can use this script which shows every notification for a specific time interval.
here is the code..
html
<div id="ccNotificationBox"></div>
css
#ccNotificationBox{
-webkit-animation-name:;
-webkit-animation-duration:2s;/*Notification duration*/
box-sizing:border-box;
border-radius:16px;
padding:16px;
background-color:rgba(0,0,0,0.7);
top:-100%;
right:16px;
position:fixed;
color:#fff;
}
#ccNotificationBox.active{
-webkit-animation-name:note;
top:16px;
}
#-webkit-keyframes note{
0% {opacity:0;}
20% {opacity:1;}
80% {opacity:1;}
100% {opacity:0;}
}
javascript
var coccoNotification=(function(){
var
nA=[],
nB,
rdy=true;
function nP(a){
nA.push(a);
!rdy||(nR(),rdy=false);
}
function nR(){
nB.innerHTML=nA[0];console.log(nA[0]);
nB.offsetWidth=nB.offsetWidth;//reflow ios
nB.classList.add('active');
}
function nC(){
nB.classList.remove('active');
nB.innerHTML='';
nA.shift();
nA.length>0?nR():(rdy=true);
}
function init(){
nB=document.getElementById('ccNotificationBox');
nB.addEventListener('webkitAnimationEnd',nC,false);
window.removeEventListener('load',init,false);
}
window.addEventListener('load',init,false);
return nP
})();
usage
coccoNotification('notification 1');
example
http://jsfiddle.net/f6dkE/1/
info
the example above is perfect for external js as you use just one global variable which is the name of the function ... in my case coccoNotification
here is a different approach but it does the same
http://jsfiddle.net/ZXL4q/11/

javascript scoping? - jquery plugin countdown timer

Hi I am having a problem where scoping seems to be lost. What I am doing wrong?
Suppose the logic is that 1 second is decreased from every counter and not from the last counter only.
What I am doing wrong?
<html>
<head>
<link rel="stylesheet" href="http://static.jquery.com/files/rocker/css/reset.css" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
(function($){
$.fn.extend({
countdown: function(options) {
var defaults = {
daysSelector : 'span.days',
hoursSelector : 'span.hours',
minutesSelector : 'span.minutes',
secondsSelector : 'span.seconds'
}
var options = $.extend(defaults, options);
var _this = $(this);
tick = function()
{
var days = _this.find(options.daysSelector);
var hours = _this.find(options.hoursSelector);
var minutes = _this.find(options.minutesSelector);
var seconds = _this.find(options.secondsSelector);
console.log(_this);
var currentSeconds=seconds.text();
currentSeconds--;
if(currentSeconds<0)
{
seconds.text("59");
var currentMinutes=minutes.text();
currentMinutes--;
if(currentMinutes<0)
{
(minutes).text("59");
var currentHours=(hours).text();
currentHours--;
if(currentHours<0)
{
(hours).text("23");
var currentDays=(hours).text();
currentDays--;
}
else
{
if(currentHours.toString().length==1)
{
(hours).text('0'+currentHours);
}
else
{
(hours).text(currentHours);
}
}
}
else
{
if(currentMinutes.toString().length==1)
{
(minutes).text('0'+currentMinutes);
}
else
{
(minutes).text(currentMinutes);
}
}
}
else
{
if(currentSeconds.toString().length==1)
{
seconds.text('0'+currentSeconds);
}
else
{
seconds.text(currentSeconds);
}
}
}
return this.each(function()
{
console.log(_this);
setInterval("this.tick()",1000);
});
}
});
})(jQuery);
$(document).ready(function()
{
$("#timer1").countdown();
$("#timer2").countdown();
$("#timer3").countdown();
});
</script>
</head>
<body>
<div id="timer1">
<span class="days">1</span>
<span class="hours">18</span>
<span class="minutes">6</span>
<span class="seconds">45</span>
</div>
<div id="timer2">
<span class="days">2</span>
<span class="hours">28</span>
<span class="minutes">1</span>
<span class="seconds">59</span>
</div>
<div id="timer3">
<span class="days">10</span>
<span class="hours">0</span>
<span class="minutes">59</span>
<span class="seconds">59</span>
</div>
</body>
I edited your code
(function($){
$.fn.extend({
countdown: function(options) {
var defaults = {
daysSelector : 'span.days',
hoursSelector : 'span.hours',
minutesSelector : 'span.minutes',
secondsSelector : 'span.seconds'
}
var options = $.extend(defaults, options);
var _this = $(this);
var tick = function()
{
var days = _this.find(options.daysSelector);
var hours = _this.find(options.hoursSelector);
var minutes = _this.find(options.minutesSelector);
var seconds = _this.find(options.secondsSelector);
console.log(_this);
var currentSeconds=seconds.text();
currentSeconds--;
if(currentSeconds<0)
{
seconds.text("59");
var currentMinutes=minutes.text();
currentMinutes--;
if(currentMinutes<0)
{
(minutes).text("59");
var currentHours=(hours).text();
currentHours--;
if(currentHours<0)
{
(hours).text("23");
var currentDays=(hours).text();
currentDays--;
}
else
{
if(currentHours.toString().length==1)
{
(hours).text('0'+currentHours);
}
else
{
(hours).text(currentHours);
}
}
}
else
{
if(currentMinutes.toString().length==1)
{
(minutes).text('0'+currentMinutes);
}
else
{
(minutes).text(currentMinutes);
}
}
}
else
{
if(currentSeconds.toString().length==1)
{
seconds.text('0'+currentSeconds);
}
else
{
seconds.text(currentSeconds);
}
}
}
return _this.each(function()
{
console.log(_this);
setInterval(tick,1000);
});
}
});
})(jQuery);
$(document).ready(function()
{
$("#timer1").countdown();
$("#timer2").countdown();
$("#timer3").countdown();
});
tick was global and that was the problem (also never pass code to be evalued to setInterval!
Fiddle here: http://jsfiddle.net/kvqWR/1/
If I have to guess what the issue is... only 1 timer actually counts down and the other two doesn't?
That's because the extended countdown timer function you have never passes the name (id) of the countdown timer through to the function. So it always only executes the last one since the last one is what was called...last.
You'd need to send through the name (id) of the div for it to count down all 3 simultaneously.
You declared tick in global scope. Make it local:
var tick = function()...
and don't pass a string to setInterval:
setInterval(tick,1000);
A better structure of your plugin would be to declare the tick function only once and pass the current element (or the time fields) as argument:
(function($){
var tick = function(days, hours, minutes, seconds) {
//...
};
$.fn.countdown = function(options) {
var defaults = {
daysSelector : 'span.days',
hoursSelector : 'span.hours',
minutesSelector : 'span.minutes',
secondsSelector : 'span.seconds'
}
var options = $.extend(defaults, options);
return this.each(function(){
var days = $(this).find(options.daysSelector);
var hours = $(this).find(options.hoursSelector);
var minutes = $(this).find(options.minutesSelector);
var seconds = $(this).find(options.secondsSelector);
setInterval(function() {
tick(days, hours, minutes, seconds);
},1000);
});
};
}(jQuery));
Then your plugin also works if you select multiple elements at once:
$("#timer1, #timer2, #timer3").countdown();
which would not work otherwise (see here http://jsfiddle.net/fkling/kvqWR/5/).
Working DEMO
It might also be better to have only setInterval going on which iterates over selected elements and performs the operation. The fewer timers you have, the better. Have a look at this example: http://jsfiddle.net/fkling/kvqWR/4/

Categories