I've used this
http://jsfiddle.net/3KydB/
and tried to modify it for 3 divs:
window.switchIn = function () {
$('.chart_1').fadeToggle(function() {
$('.chart_2').fadeToggle(function() {
$('.chart_3').fadeToggle(function() {
setTimeout(function() {window.switchOut();}, 6000);
});
});
});
}
window.switchOut = function () {
$('.chart_3').fadeToggle(function() {
$('.chart_2').fadeToggle(function() {
$('.chart_1').fadeToggle(function() {
setTimeout(function() {window.switchIn();}, 6000);
});
});
});
}
setTimeout(function() {window.switchIn();}, 6000)
The first one fades in and out fine, then the second one fades in with the third one below it, then back to the first one etc.
I think you would want something like the following: http://jsfiddle.net/mEeAt/
window.switch1 = function () {
$('.chart_3').fadeToggle(function() {
$('.chart_1').fadeToggle(function() {
setTimeout(window.switch2, 6000);
});
});
}
window.switch2 = function () {
$('.chart_1').fadeToggle(function() {
$('.chart_2').fadeToggle(function() {
setTimeout(window.switch3, 6000);
});
});
}
window.switch3 = function () {
$('.chart_2').fadeToggle(function() {
$('.chart_3').fadeToggle(function() {
setTimeout(window.switch1, 6000);
});
});
}
setTimeout(window.switch2, 6000)
So each function is responsible for fading out the active element, fading in the next element, and setting a timeout for the next function in the cycle.
Of course there is a lot of repeated code here, so you would probably be better off creating a function to make this more generic: http://jsfiddle.net/mEeAt/1/
function cycle(delay) {
var elements = Array.prototype.slice.call(arguments, 1);
var functions = [];
for (var i = 0; i < elements.length; i++) {
functions.push(function (i) {
var prev = i === 0 ? elements.length - 1 : i - 1;
var next = (i + 1) % elements.length;
return function() {
elements[prev].fadeToggle(function() {
elements[i].fadeToggle(function() {
setTimeout(functions[next], delay);
});
});
};
}(i));
}
functions[1](); // start cycle by fading in the second element
}
cycle(6000, $('.chart_1'), $('.chart_2'), $('.chart_3'));
Related
I have a onload function in jquery like:
$(function () {
$('.over').hover(function () {
//FIRST PARAMETER RIGT, LEFT, TOP, BOTTOM
if ($(this).attr('data-direction') == 'right') {
$(this).addClass('flipping-right');
}
else if ($(this).attr('data-direction') == 'left') {
$(this).addClass('flipping-left');
}
else if ($(this).attr('data-direction') == 'top') {
$(this).addClass('flipping-top');
}
//ETC.
//SECOND gal1,gal2,gal3,gal4
if ($(this).attr('gal') == 'gal1'){
img = $(this).find('img');
setTimeout(function() {
img.attr('src', arrFirstYellowCard[i]);
i++;
if(i > arrFirstYellowCard.length-1)
i=0;
}, 100);
}
else if ($(this).attr('gal') == 'gal2'){
img = $(this).find('img');
setTimeout(function() {
img.attr('src', arrSecondPurpleCard[j]);
j++;
if(j > arrSecondPurpleCard.length-1)
j=0;
}, 100);
}
I want a function to execute that function every second but with parameters in array like
var array_param = ["right,gal1","top,gal3","bottom,gal4","left,gal2","right,gal5"];
which are allowed combinations
I want like a timer so each parameter is called every second
var timer = $.timer($('.over').hover(array_param( 0 ) ), 1000);
timer.play();
but I do not know how to implement this function, and how to add parameters to a function allocated in onload :
$(function () { $('.over').hover(function () {...
Please take a look at my jsfiddle
You can't trigger ready again. You can create a named function and call it a bunch.
$(function () {
index = 0;
window.setInterval(function () {
if (index > array_param.length) index = 0;
myFunction(array_param[index++]);
}, 1000); // call myFunction every second
});
myFunction = function (image) {
$('.over').hover(function () {
// rest of your code goes here
...
};
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/
I have this jQuery function that work. Every 2 lines is the same except a minor changes. How can I shorten it?
$(".c1").delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c2").fadeIn("slow", function() {
$(".c2").delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c3").fadeIn("slow", function() {
$(".c3").delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c4").fadeIn("slow", function() {
$(".c4").delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c5").fadeIn("slow", function() {
$(".c5").delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c6").fadeIn("slow", function() {
$(".c6").delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c7").fadeIn("slow", function() {
$(".c7").delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c8").fadeIn("slow", function() {
$(".c8").delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c9").fadeIn("slow", function() {
$(".c9").delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c1").fadeIn("slow");
});
});
});
});
});
});
});
});
});
});
});
});
});
});
});
});
});
});
You could use a recursive function like this:
function phoneCall(i){
$(".c" + i).delay(5000).fadeOut("slow", function() {
$("#phone").addClass("c" + (i + 1)).fadeIn("slow", function() {
if(i <= 9) phoneCall(i + 1);
});
});
}
phoneCall(1);
It seems that the #phone element is the only one that ever gets the c_ class. If so, you can cache the element and eliminate a bunch of code.
var phone = $("#phone"), i = 0;
(function cycle() {
i = ((i % 9) + 1);
phone.addClass("c" + i).fadeIn("slow").delay(5000).fadeOut("slow", cycle);
})();
We can even get rid of a line of code by inlining the increment.
var phone = $("#phone"), i = 0;
(function cycle() {
phone.addClass("c" + ((++i % 9) + 1)).fadeIn("slow").delay(5000).fadeOut("slow", cycle);
})();
As #charlietfl noted, you may not want it to infinitely loop. If not, add a return statement.
var phone = $("#phone"), i = 0;
(function cycle() {
if (i === 9) return;
phone.addClass("c" + ((++i % 9) + 1)).fadeIn("slow").delay(5000).fadeOut("slow", cycle);
})();
And FWIW, numbering is usually a little simpler if you use 0 based indices.
var phone = $("#phone"), i = -1;
(function cycle() {
phone.addClass("c" + (++i % 9)).fadeIn("slow").delay(5000).fadeOut("slow", cycle);
})();
You can use something like that:
function inception(fromInt, tillInt){
if (fromInt < tillInt){
$('.c' + fromInt).delay(5000).fadeOut("slow",function(){
newInt = fromInt +1;
$('#phone').addClass('c'+newInt).fadeIn("slow", function() {
inception(newInt, tillInt));
}
});
}else{
if(fromint == tillInt){
$('.c' + fromInt).delay(5000).fadeOut("slow");
}
}
}
Then add to your code:
inception(1,9);
I don't know something like this?
var num = 2;
var HandlerForC = function () {
if (num < 10) {
$("#phone").addClass("c" + num).fadeIn("slow", HandlerForPhone);
} else {
$("#phone").addClass("c1").fadeIn("slow");
}
}
var HandlerForPhone = function () {
num++;
$(".c" + (num - 1)).delay(5000).fadeOut("slow", HandlerForC);
}
HandlerForPhone();
We had a developer work-up a piece of javascript for animating markers on a map for us. See http://luniablue.com/clients/endowment for it's current state.
The issue I'm having, is that the rollover is too sensitive and I want there to be a 1sec pause before executing the rollover function. From what I've read, I need to declare a setTimeout() function, but I'm not clear on where to insert that.
I have tried every place that I can see and I've had no luck except in breaking the script. I'm sure it's something stupid simple, but javascript isn't my stong point. Can anyone help me out?
Here's the code:
var firstEntry = true;
var lastOn = '';
function showAllPins() {
if ($('#communities').hasClass('theMouseIsOff')) {
var citiesArr = [];
$('.pin').each( function () {
citiesArr.push(this.id);
$('#'+this.id).hide();
});
var stillHidden = citiesArr.length;
while (stillHidden > 0) {
var a = Math.floor(Math.random()*citiesArr.length);
if ($('#'+citiesArr[a]).is(':hidden')) {
$('#'+citiesArr[a]).show().delay(Math.floor(Math.random()*900)).animate({
opacity: 1,
top: '+=40',
}, Math.floor(Math.random()*900), 'easeOutBounce');
stillHidden--;
}
}
firstEntry = true;
$('#communities').removeClass('theMouseIsOff');
}
}
function showPin(relid){
lastOn = relid;
if ($('#communities').hasClass('theMouseIsOff')) $('#communities').removeClass('theMouseIsOff');
if (firstEntry == true) {
$("#communities div[id!=" + relid + "].pin").animate({
opacity: 0,
top: '-=40',
}, 500);
firstEntry = false;
} else {
$("#communities div[id=" + relid + "].pin").animate({
opacity: 1,
top: '+=40',
}, 500, 'easeOutBounce');
}
}
function removeLastPin() {
$('#communities').addClass('theMouseIsOff');
$("#communities div[id=" + lastOn + "].pin").animate({
opacity: 0,
top: '-=40',
}, 500);
setTimeout('showAllPins()',600);
}
$(document).ready( function () {
$('.pin').mouseenter( function () {
relid = $(this).attr('rel');
showPin(relid);
}).mouseleave( function () { removeLastPin() });
});
$(document).ready(function() {
$('.pin').each(function() {
var selector = '#' + $(this).data('tooltip-id');
Tipped.create(this, $(selector)[0], { skin: 'light', hook: { target: 'topmiddle', tooltip: 'bottomleft'}});
});
});
Where you see:
$(document).ready( function () {
$('.pin').mouseenter( function () {
relid = $(this).attr('rel');
showPin(relid);
}).mouseleave( function () { removeLastPin() });
});
You can change it to:
$(document).ready( function () {
$('.pin').mouseenter( function () {
relid = $(this).attr('rel');
setTimeout(function(){showPin(relid)}, 1000);
}).mouseleave( function () { removeLastPin() });
});
By changing the showPin() function to execute after a timeout, the pin should appear after the specified interval.
Update:
If you would like the function only to run if the mouseleave hasn't occurred during the specified interval, you can clear the interval on mouseleave like this:
$(document).ready(function() {
$('.pin').mouseenter(function() {
relid = $(this).attr('rel');
var awaiting = setTimeout(function() {
showPin(relid)
}, 1000);
}).mouseleave(function() {
removeLastPin();
clearInterval(awaiting);
});
});
I have this code:
js:
function change_color(color) {
$("body").animate({ backgroundColor:color }, '1000');
}
setTimeout(function () {
change_color('#4AC900'
);
}, 500);
setTimeout(function () {
change_color('#964514'
);
}, 1500);
setTimeout(function () {
change_color('#EE0000'
);
}, 1500);
setTimeout(function () {
change_color('#FFE303'
);
}, 1500);
setTimeout(function () {
change_color('#8E388E'
);
}, 1500);
setTimeout(function () {
change_color('#FF00AA'
);
}, 1500);
and I want to use it repeatedly but putting it in a while loop just crashes the site can anyone help?
Here is the site... its my little brothers site not mine... http://timothy.techbytbone.com/isaac.php
var colors = ['#4AC900', '#964514', '#EE0000', '#FFE303', '#8E388E', '#FF00AA'],
len = colors.length,
i;
for (i = 0; i < len; i++) {
(function(i, color) {
setTimeout(function () {
change_color(color);
}, (i + 1) * 500);
})(i, colors[i]);
}
this is all you need:
jsFiddle demo
var c = 0;
var colors = ['#4AC900','#964514','#EE0000','#FFE303','#8E388E','#FF00AA'];
(function loop(){
$('body').stop().animate({backgroundColor : colors[c++%colors.length] }, 1000, loop);
})();
(Prest attention that you need to use the jQuery UI to animate the CSS background-color property)
var colors = {'#4AC900': 500,
'#964514': 1500,
// etc. Just continue with the color-millisecond combinations
}
for(key in colors) {
setTimeout(function () {
change_color(key);
}, colors[key]);
}
Your loop is crashing because you can't set all the necessary timeouts at browser's loading. Here is a version of your code that should work.
var colors = ['#4AC900', '#964514', '#EE0000', '#FFE303', '#8E388E', '#FF00AA'];
var currentColorIndex = 0;
var scheduleChange;
scheduleChange = function() {
change_color(currentColorIndex);
currentColorIndex = (currentColorIndex + 1) % colors.length
setTimeout(scheduleChange, 1000);
};
setTimeout(scheduleChange, 500);
function change_color(color) {
$("body").animate({ backgroundColor:color }, '1000');
}
setTimeout(function() {
change_color('#4AC900')
}, 500);
colors = ['#964514', '#EE0000', '#FFE303', '#8E388E', '#FF00AA']
interval = setInterval(function() {
if (! a.length) {
return clearInterval(interval);
}
change_colors(a.shift());
}, 1500);
Have Fun. You should learn about closures for not messing setIntervals. There are tons of libraries that animate colors and other stuff. I can recommend morpheus by ded.