jquery delay document ready function by number of seconds? - javascript

I have a div called noti_box which fades in on page load. Sometimes there may be only one noti_box div or there might be 2 3 or 4.
a user can close this div should they want to by clicking on it.
If no noti_boxes are displayed on the page I am trying to fade in another div, lets call this div (advert).
however with my current script I have, because my first div noti_box takes a couple of seconds to fade in it will automatically show my advert div. what should happen is my advert div should only show once the user has closed the div noti_box, not before it fades in on the page.
Is there a way I can delay my jquery function to wait until the noti_box has finished fading in?
noti_box jquery:
<script>
$('.noti_box').each(function(i) {
// 'i' stands for index of each element
$(this).hide().delay(i * 1000).fadeIn(1500);
});
</script>
my advert div jquery:
<script type="text/javascript">
$(document).ready(function(){
if ($('.noti_box').is(':hidden')) {
$(".advert").fadeIn("slow");
}
}); </script>
I have gotten close to what I need:
<script>
$(document).ready(function(){
var animations = [];
$('.noti_box').each(function(i) {
animations.push(
$(this).hide().delay(i * 1000).fadeIn(1500).promise()
);
});
$.when.apply($, animations).done(function () {
if ($('.noti_box').is(':visible')===false) {
$(".advert").fadeIn("slow");
}});
});
</script>
by using this script my noti_boxes fade in and if I close them within like 1 second of them fading in then my advert box fades in. however if I wait after 1 second then I close the noti_boxes my advert doesn't fade in at all. Any ideas?

Since you know the amount of elements and the amount of time each takes to fade, you can calculate the total needed delay for the advert to show, something like this:
// number of elements * their delay + fade time
var totalDelay = ($('.noti_box').length - 1) * 1000 + 1500;
$(document).ready(function(){
setTimeout(function(){
$(".advert").fadeIn("slow");
}, totalDelay);
});
Here's an example with 5 noti boxes (can be any number):
$('.noti_box').each(function(i) {
// 'i' stands for index of each element
$(this).hide().delay(i * 1000).fadeIn(1500);
});
// number of elements * their delay + fade time
var totalDelay = ($('.noti_box').length - 1) * 1000 + 1500;
$(document).ready(function() {
setTimeout(function() {
$(".advert").fadeIn("slow");
}, totalDelay);
});
.advert {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="noti_box">1</div>
<div class="noti_box">2</div>
<div class="noti_box">3</div>
<div class="noti_box">4</div>
<div class="noti_box">5</div>
<div class="advert">ADVERT</div>

Try putting document.ready in Javascript SetTimeout function.

I found the answer to my question, I set a time interval for my last function to repeat every second.
<script>
$(document).ready(function(){
var animations = [];
$('.noti_box').each(function(i) {
animations.push(
$(this).hide().delay(i * 1000).fadeIn(1500).promise()
);
});
$.when.apply($, animations).done(function () {
time=setInterval(function(){
if ( $('.noti_box:visible').length === 0 ) {
$(".advert").fadeIn("slow");
} },1000);
});
});
</script>

Related

2 setTimeout in Javascript not working properly

I manage to create my first function to hide and display div, But when I try to use 2 setTime out the other div is loading infinitely, What I need to do is to display div in diffrent set of time, any idea ?
Here is JS my code
function showDiv1() {
// If there are hidden divs left
if ($('.forHide:hidden').length) {
// Fade the first of them in
$('.forHide:hidden:first').fadeIn();
if ($('.forHide:hidden').length >= 1) {
$(".forHide").fadeOut(1500, function() {});
}
// And wait one second before fading in the next one
myVar = setTimeout(showDiv1, 100);
}
}
function showDiv2() {
// If there are hidden divs left
if ($('.forSlowMo:hidden').length) {
// Fade the first of them in
$('.forSlowMo:hidden:first').fadeIn();
if ($('.forSlowMo:hidden').length >= 1) {
$(".forSlowMo").fadeOut(1500, function() {});
}
// And wait one second before fading in the next one
setTimeout(showDiv2, 1000);
}
}
After .fadeIn of the first item, if there are any more hidden, the code currently fades them all out:
$('.forSlowMo:hidden:first').fadeIn();
if ($('.forSlowMo:hidden').length >= 1) {
// this line selects all, including the one just shown
$(".forSlowMo").fadeOut(1500, function() {});
}
You need to exclude the one you've just shown:
var x = $('.forSlowMo:hidden:first').fadeIn();
if ($('.forSlowMo:hidden').length >= 1) {
$(".forSlowMo").not(x).fadeOut(1500, function() {});
}
Updated fiddle: https://jsfiddle.net/hd8q1mox/1/
In the fiddle, I've removed the .forHide part so you can see the difference on the .slowMo as they appear on top of each other.

delay between animate.css animations

I'm kind of new to jQuery and I'm currently trying the following:
I'm using animate.css to animate a div. What I want to do now is to define a timing between fading in and fading out. For example:
Fade in > 3 sec delay > fade out
I'm using this function to dynamically add classes from animate.css to my object (#test).
$(document).ready(function () {
phase1('#test', 'bounceInLeft');
function phase1(element, animation) {
element = $(element);
element.addClass('animated ' + animation);
};
});
I'm trying to archive something like this:
phase1('#test', 'bounceInLeft');
3 sec delay
phase1('#test', 'bounceOutLeft');
1 sec delay
phase1('#test2', 'bounceInLeft');
.....
Any kind of help is really appreciated :) Thanks in advance!
Yes you setTimeout. Wrap your code within this section and adjust the timing with the amount of milliseconds that you want. This allows you to stagger code timings with multiple values..
This example will delay by three seconds, then one by five seconds..
setTimeout(function(){
// place your code in here
}, 3000);
setTimeout(function(){
// place your second bit of code in here
}, 5000);
Since you are using jQuery, you can use animation chains like that
(function($){
$(".move")
.animate({left:"+=200"},3000)
.delay()
.animate({left:"+=100"},3000);
})(jQuery);
See Example
Using jQuery chain events
$("#id").fadeIn(1000).delay(3000).fadeOut(1000);
This should work for you. All parameters specify time 1000=1Sec
http://jsfiddle.net/k8zq2fo6/
You can increase the chain
$("#id").fadeIn(1000).delay(3000).fadeOut(1000).delay(2000).fadeIn(1000).delay(3000).fadeOut(1000).delay(2000);
Try utilizing .queue()
$(function() {
// load `Animate.css`
$("style").load("https://raw.githubusercontent.com/"
+ "daneden/animate.css/master/animate.css");
// animation settings
var settings = [{
"bounceInLeft": 3000
}, {
"bounceOutLeft": 1000
}, {
"bounceInLeft": 3000
}];
$("#test").queue("bounce", $.map(settings, function(val, key) {
return function(next) {
var current = Object.keys(val)[0];
$(this)
// reset `className`
.attr("class", "")
// add `animated` , `current` `class`
.addClass("animated " + current);
// log `.queue("bounce")` iteration
console.log(this.className, current
, settings[key][current], $(this).queue("bounce"));
// "delay": `settings[key][current]` ,
// call `next` function in `.queue("bounce")`
setTimeout(next, settings[key][current]);
}
}))
.dequeue("bounce")
// do stuff when `.queue("bounce")` empty
.promise("bounce")
.then(function(elem) {
console.log(elem.queue("bounce"), "complete")
})
});
#test {
position: relative;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">abc</div>
<style></style>

Execute two divs in same javascript

I'm trying fade effect in two different div classes at same same-time. For that i need two different scripts, and executing same script for two div(s), it lags. Is there any way to execute both divs in same script like
(.fadein,.fadeo)? FIDDLE- jsfiddle.net/562am/.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script> //Function 1
$(function(){
$('.fadeo img:gt(0)').hide();
setInterval(function(){$('.fadeo :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadeo');}, 2000);
});
</script>
<script> //Function 2
$(function(){
$('.fadein img:gt(0)').hide();
setInterval(function(){$('.fadein :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadein');}, 2000);
});
</script>
Is this what you meant by combining the two into 1 function?
$(function(){
var classes = ['.fadeo', '.fadein'];
$.each(classes, function (index, elem){
var selectorToHide = elem + ' img:gt(0)',
selectorToFadeOut = elem + ' :first-child';
$(selectorToHide).hide();
setInterval(function() {
$(selectorToFadeOut)
.fadeOut()
.next('img')
.fadeIn()
.end()
.appendTo(elem);
},
2000);
});
});
2 setInterval run on their own - they may produce lags. The correct way is to use 1 interval and do the whole logic there.
With appendTo you're changing the DOM every 2 seconds. This method causes extra performance issues and leads to slower application run. I would suggest you to keep an index with the current image, and change it as you want (this is shown below).
In my example I've calculated the minimum number of images (if separate divs have different image count).
$(function () {
// a value can be fixed - a constant
var imagesCount = Math.min($('.fadeo > img').size(),
$('.fadein > img').size());
var i = 0;
display(i);
setInterval(function () {
i = (i+1) % imagesCount;
display(i);
}, 2000);
});
function display(nth) {
$('.fadeo > img').hide().eq(nth).show();
$('.fadein > img').hide().eq(nth).show();
}

Slideshow Background <body> tag

When a user loads my page I want to let the background color be white then after 5 seconds fade away the color and fade in the picture. And after 5 seconds fade in another picture again so you can create sort of a slide show in the background behind my content. This is what I have now but it doesn't work, any help?
$(document).ready(function() {
setTimout(function() {
$('body').css("background-image","url('../img/background/1.jpg')").fadeIn(1000)
},5000);
function repeat() {
$('body')
.delay(5000).css("background-image","url('../img/background/2.jpg')").fadeIn(1000)
.delay(5000).css("background-image","url('../img/background/3.jpg')").fadeIn(1000)
.delay(5000).css("background-image","url('../img/background/1.jpg')").fadeIn(1000);
}
window.setInterval(repeat, 18000);
});
The following is a syntax error:
setTimout(function() {
$('body').css("background-image","url('../img/background/1.jpg')").fadeIn(1000)
},5000);
Should be
setTimeout(function() {
$('body').css("background-image","url('../img/background/1.jpg')").fadeIn(1000)},5000);
It is missing the e in setTimeout
I also do not believe you will be able to fadeIn the background image unless you are setting it on a DIV unless you fadeOut the body. I have re-written your background changer into fewer lines of code that repeat with a list of images provided. This should keep looping for the images you have in the array.
$(document).ready(function () {
var images = ["../img/background/1.jpg", "../img/background/2.jpg"];
var index = -1;
window.setInterval(function () {
index = (index + 1 < images.length) ? index + 1 : 0;
$('body').css("background-image", "url('" + images[index] + "')");
}, 5000);
});

Transition positioning

I have some code that I would like to integrate into the a website and have it be in the middle of the screen. This code does some fading with Javascript. But I can't move it around the screen like I would like to. When I move it around it messes up the animation.
Here is the HTML
<!DOCTYPE html>
jQuery fade-ins with a JavaScript for() loop
<div id="elem0" class="toBeFaded">Here's the first message...</div>
<div id="elem1" class="toBeFaded">We have second one here...</div>
<div id="elem2" class="toBeFaded">And here's the third message...</div>
<div id="elem3" class="toBeFaded">OMG!!! Here's the fourth message!</div>
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/fadeCode.js" defer="defer"></script>
​
Javascript
$(function (){
var yourFade = 1, // the amount of time in seconds that the elements will fade in AND fade out
yourDelay = 2, // the amount of time in seconds that there will be a delay between the fade ins and fade outs
fadeTime = yourFade * 1000, //convert fade seconds to milliseconds (1000)
delayTime = yourDelay * 1000, // convert delay seconds to milliseconds (2000)
totalTime = fadeTime + delayTime, //3000 milliseconds...needed for all those delays we talked about
allElems, // find out exactly how many page elements have the 'toBeFaded' class (4)
elemNoFade, // Will help us find the last element represent the last element (3)
i,
fadingElem;
for (i = 0, allElems = $('.toBeFaded').length, elemNoFade = allElems - 1; i < allElems; i+=1) {
fadingElem = "#elem" + i;
if (i === 0) {
$(fadingElem).fadeIn(fadeTime).delay(delayTime).fadeOut(fadeTime);
} else if (i === elemNoFade) {
$(fadingElem).delay(totalTime * i).fadeIn(fadeTime);
} else {
$(fadingElem).delay(totalTime * i).fadeIn(fadeTime).delay(delayTime).fadeOut(fadeTime);
}
} });​
and CSS
.toBeFaded {
display: none;
position:absolute;
font-size:70pt;
}​
and a link to jsfiddle
I'm not sure I see the problem. Take a look at this fiddle: http://jsfiddle.net/joplomacedo/6xfKN/375/

Categories

Resources