Using setTimeout to delay timing of jQuery actions - javascript

I am attempting to delay the swapping of text in a div. It should operate like a slider/carousel for text.
I must have the code wrong, as the final text replacement never happens.
Also, how would I animate introducing the replacement text (window blinds, for eg.)?
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function() {
$("#showDiv").click(function() {
$('#theDiv').show(1000, function() {
setTimeout(function() {
$('#theDiv').html('Here is some replacement text', function() {
setTimeout(function() {
$('#theDiv').html('More replacement text goes here');
}, 2500);
});
}, 2500);
});
}); //click function ends
}); //END $(document).ready()
</script>
</head>
<body>
Below me is a DIV called "theDiv".<br><br>
<div id="theDiv" style="background-color:yellow;display:none;width:30%;margin:0 auto;">
This text is inside the Div called "theDiv".
</div><br>
<br>
<input type="button" id="showDiv" value="Show DIV">
</body>
</html>

.html() only takes a string OR a function as an argument, not both. Try this:
$("#showDiv").click(function () {
$('#theDiv').show(1000, function () {
setTimeout(function () {
$('#theDiv').html(function () {
setTimeout(function () {
$('#theDiv').html('Here is some replacement text');
}, 0);
setTimeout(function () {
$('#theDiv').html('More replacement text goes here');
}, 2500);
});
}, 2500);
});
}); //click function ends
jsFiddle example

Try this:
function explode(){
alert("Boom!");
}
setTimeout(explode, 2000);

You can also use jQuery's delay() method instead of setTimeout(). It'll give you much more readable code. Here's an example from the docs:
$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );
The only limitation (that I'm aware of) is that it doesn't give you a way to clear the timeout. If you need to do that then you're better off sticking with all the nested callbacks that setTimeout thrusts upon you.

This is how I solved the problem
The menu closes a few seconds after mouse out (that if hover didn't fire),
//Set timer switch
$setM_swith=0;
$(function(){
$(".navbar-nav li a").click(function(event) {
if (!$(this).parent().hasClass('dropdown'))
$(".navbar-collapse").collapse('hide');
});
$(".navbar-collapse").mouseleave(function(){
$setM_swith=1;
setTimeout(function(){
if($setM_swith==1) {
$(".navbar-collapse").collapse('hide');
$setM_swith=0;}
}, 3000);
});
$(".navbar-collapse").mouseover(function() {
$setM_swith=0;
});
});

Related

Execute Javascript after Div populated with Javascript has loaded

I am trying to exceute a javascript function after another div that has been popupated by javascript has loaded. The div has been populated first with javascript is '#am-events-booking'. The function i am trying to use is:
$(window).load(function ()
{
var i = setInterval(function ()
{
if ($('#am-events-booking').length)
{
clearInterval(i);
}
}, 1000);
alert('Page is loaded');
});
I always use $(document).ready() to run code after the page has loaded. Not sure what the difference is, but at least then it works.
Furthermore you need to use .text() to get the text inside an element.
Working code snippet:
$(document).ready(function() {
var i = setInterval(function() {
if ($('#am-events-booking').text().length) {
clearInterval(i);
console.log('Text detected!');
} else {
console.log('Waiting...');
}
}, 1000);
console.log('Page is loaded');
});
setTimeout(loadText, 2200);
function loadText() {
$('#am-events-booking').html("<h2>Hello</h2>");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="am-events-booking"></div>
$(document).ready(findDiv);
function findDiv() {
if($('#am-events-booking').is(':visible')){ // if the div is visible
alert('Page is loaded');
} else {
console.log("loading...");
setTimeout(findDiv, 50); // wait 50ms,
}
}
$('body').html('<div id="am-events-booking"></div>');
<body></body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
you can use is :visible form JQuery to check if div is added or not

JQuery: Wait until all fadeout`s of function are finished

I have next function:
function clearWorkingArea() {
$('.extensionText').children('span').fadeOut(600, function() { $(this).remove() });
$('ul.texts').fadeOut(600, function() { $(this).empty() });
$('.buttonsDiv').fadeOut(600, function() { $(this).remove() });
$('.processingDiv').fadeOut(600, function() { $(this).remove() });
}
I would like to call another function only after all animations in this function are finished.
I tried :
$.when(clearWorkingArea()).done(function() {...});
Also:
clearWorkingArea().promise().done(function() {...});
No luck, it is still not working properly.
Is there is a way, instead of callback hell of fades, to do such function behavior?
Update: just double checked jquery, animations can return a promise. I initially just did promise, but to get a promise with jquery you do promise(). So you don't need the helper function after all.
Below is an example.
Also if you have multiple selectors doing the same thing, you can combine.
eg. below .two & .three fadeOut at 600ms, but I've made .one fadeOut over 1000ms. Also added a none-existent selector to make sure things still work.
Promise.all(
[
$('.one').fadeOut(1000, function () {
$(this).empty(); }).promise(),
$('.two,.three').fadeOut(600, function () {
$(this).empty(); }).promise(),
$('.not-exist').fadeOut(600, function () {
$(this).empty(); }).promise()
]
).then(function () {
console.log('all done');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">
Three 1000 ms
</div>
<div class="two">
One 600 ms
</div>
<div class="three">
Two 600 ms
</div>
clearWorkingArea only starts the animations, but these animations are all async.
At the end of clearWorkingArea, your animations are unlikely to be over.
You have to fetch a promise for each animation and then use Promise.all to trigger your code when all promises are over.
According to the documentation, you can get the promise by using the start parameter in the options of fadeOut like methods:
jQuery fadeOut()
Hope this helps!
How about we apply some simple logic like this.
function doWorkWhenAllFinished(counter) {
if (counter == 4) {
//All fade animations have been complete.
//Good to go...
}
}
function clearWorkingArea() {
var counter = 0;
$('.extensionText').children('span').fadeOut(600, function() {
counter++;
$(this).remove();
doWorkWhenAllFinished(counter);
});
$('ul.texts').fadeOut(600, function() {
counter++;
$(this).empty();
doWorkWhenAllFinished(counter);
});
$('.buttonsDiv').fadeOut(600, function() {
counter++;
$(this).remove();
doWorkWhenAllFinished(counter);
});
$('.processingDiv').fadeOut(600, function() {
counter++;
$(this).remove();
doWorkWhenAllFinished(counter);
});
}

jQuery hide and show effect seen at function end

Consider the following code:
<div id="thediv" >hola</div>
<button id="resharper">button</button>
with javascript/jQuery:
$("button").on( 'click', function() {
$("#thediv").show();
alert('click');
});
$(document).ready(function(){
$("#thediv").hide();
})
I want the behavior to first show the div tag and then display the alert "Click". Instead the behavior works in the opposite way. Alert text is first displayed followed by the button being visible. Am i missing something ?
Can i modify the code somehow to get the desired behavior where the div is first displayed and then alert text is flashed.
Check that in jQuery.show(options) allows you to pass a PlainObject options.
And than you can use complete: A function that is called once the animation on an element is complete.
Code:
$("button").on( 'click', function() {
$("#thediv").show({
complete: function() {
alert('click');
}
});
});
$(document).ready(function(){
$("#thediv").hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thediv" >hola</div>
<button id="resharper">button</button>
with javascript/jQuery:
It's because the alert() blocks the UI thread from updating, and that thread has not yet had time to show the element in the DOM before you call the alert().
Ideally you should use console.log() for debugging, however you can avoid this issue by putting the alert() in a setTimeout() with a very short delay.
$("button").on( 'click', function() {
$("#thediv").show();
setTimeout(function() {
alert('click');
}, 10);
});
#thediv { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thediv" >hola</div>
<button id="resharper">button</button>
with javascript/jQuery:
$("button").on('click', function() {
$("#thediv").show("slow", callback);
});
$(document).ready(function() {
$("#thediv").hide();
})
function callback() {
alert('click');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thediv">hola</div>
<button id="resharper">button</button>
Add parameter to .show()

It works using div on body. It doesn't using get

Status: WORKING
Runs smoothly - click works
Jquery
$("document").ready(function(){
$("#test").click(function(){
alert("abc");
});
});
CSS
.blue {
background-color:blue;
}
Tag Body
<body>
<div class="blue" id="test">Testing code</div>
</body>
Status: NOT WORKING
Succeeds to add the file and div test within it but click doesn't work
Jquery
$("document").ready(function(){
$.get("new.php", {
// this math avoids IE from crashing
nbRandom: Math.random()
},
function(data){
$("body").html(data);
});
$("#test").click(function(){
alert("abc");
});
});
CSS
.blue {
background-color:blue;
}
Tag Body
<body>
</body>
Does anybody know how to do that?
The method get is asynchronous which means that the stream will continue while the ajax request is still running, the best solution is to put the click handler into the get callback.
$("document").ready(function(){
$.get("new.php", {
// this math avoids IE from crashing
nbRandom: Math.random()
},
function(data){
$("body").html(data);
$("#test").click(function(){
alert("abc");
});
});
});
You should delegate the event, from one of static parents of the element or document object.
$(document).on("click", "#test", function(){
alert("abc");
})
use delegate or on(recommend)
$(function() {
$('body').on('click', '#test', function() { alert('abc'); });
// or
// $('body').delegate('#test', function() { alert('abc'); });
});
problem is the the click function is called before the div with #test is appended...
call click function after the div is appended.. so that it gets that id... and the event
try this
$.get("new.php", {
// this math avoids IE from crashing
nbRandom: Math.random()
},
function(data){
$("body").html(data);
$("#test").click(function(){
alert("abc");
});
});
OR
the on function with selector as document..(i alway prefer to go with this)
$(document).on("click", "#test", function(){
alert("abc");
})

jQuery delay between animations

I have two elements that shouldn't be active at the same time, so when one is toggled I fade the other out, however I would like to be able to fade the open element out and then bring the other one in. Is there a way to do this that isn't a hack?
<script ="text/javascript">
$(function() {
$('#jlogin').click(function() {
$('#login').toggle('fast');
$('#reg').fadeOut('fast');
});
$('#jreg').click(function() {
$('#reg').toggle('fast');
$('#login').fadeOut('fast');
});
});
</script>
That is my current script.
Look at using the callback mechanism for fadeOut so you can chain the animations. The callback on the animation methods are called after the previous animation is complete.
<script type="text/javascript">
$(function() {
$('#jlogin').click(function() {
$('#reg').fadeOut('fast', function() {
$('#login').toggle('fast');
});
});
$('#jreg').click(function() {
$('#login').fadeOut( 'fast', function() {
$('#reg').toggle('fast');
});
});
});
</script>

Categories