I have the following function (I've removed code from the middle that is not important to my question):
function shadowBoxRefresh(){
$("#sb-nav-next, #sb-nav-previous").click(function(){
$('#sb-container').addClass("visibility_stay");
$('#sb-overlay').addClass("opacity_stay");
Shadowbox.close();
Shadowbox.clearCache();
shadowBoxSetup();
setTimeout("Shadowbox.open(c)", 400)
$('#sb-container').removeClass("visibility_stay");
$('#sb-overlay').removeClass("opacity_stay");
}
});
}
My problem is, I need this part:
$('#sb-container').removeClass("visibility_stay");
$('#sb-overlay').removeClass("opacity_stay");
to fire after the rest of the function has completed. I'm wondering if a callback would do the job, but I'm not versed well enough in callbacks to know how to implement it.
Your help would be much appreciated.
If by "after the rest of the function" you mean, "after the Shadowbox.open(c)" that happens .4 sec later, then do this:
function shadowBoxRefresh(){
$("#sb-nav-next, #sb-nav-previous").click(function(){
$('#sb-container').addClass("visibility_stay");
$('#sb-overlay').addClass("opacity_stay");
Shadowbox.close();
Shadowbox.clearCache();
shadowBoxSetup();
setTimeout(function () {
Shadowbox.open(c);
$('#sb-container').removeClass("visibility_stay");
$('#sb-overlay').removeClass("opacity_stay");
}, 400);
}
});
}
Assuming after shadowBoxSetup() is when you want it
function shadowBoxSetup( callback ) {
// Your code...
callback();
}
To use that
function shadowBoxRefresh(){
$("#sb-nav-next, #sb-nav-previous").click(function(){
$('#sb-container').addClass("visibility_stay");
$('#sb-overlay').addClass("opacity_stay");
Shadowbox.close();
Shadowbox.clearCache();
shadowBoxSetup(function(){
$('#sb-container').removeClass("visibility_stay");
$('#sb-overlay').removeClass("opacity_stay");
});
setTimeout("Shadowbox.open(c)", 400);
}
});
}
It will be executed after the rest of the function has completed; statements are executed in order.
Are you saying you want it to execute after the timeout? If so, create a function that encapsulates the two calls and the open() call.
If not, you might need to be a bit clearer.
Related
As I was making a gallery for a webpage I ran into a problem with js automatically running the (next_image) function, after some searching around I found out it was due to the () after the statement.
however, I can not for the life of me figure out how else to get the clicked_id to the next_image function.
So my question is: how can I make it so that the function runs only after clicking the button while still sending the clicked_id?
function opencase(clicked_id) {
document.getElementById("right_arrow").addEventListener("click", next_image(clicked_id));
}
function next_image(photoid){
console.log(photoid);
photoid++;
document.getElementById("disp").setAttribute("src", "images/image"+photoid+".jpg");
console.log(photoid);
}
Any help will be greatly appreciated :D
Instead of directly calling the function , call it from the addEventListener callback function
function opencase(clicked_id) {
document.getElementById("right_arrow").addEventListener("click", function() {
next_image(clicked_id)
});
}
function next_image(photoid) {
console.log(photoid);
photoid++;
document.getElementById("disp").setAttribute("src", "images/image" + photoid + ".jpg");
console.log(photoid);
}
why does setTimeout not work? And how to do this action properly? I need to get 30s delay every submit. Sorry for newbie question, but i am newbie.
if (event.target.id.indexOf('submit') === 0)
{ post1000.submit(); setTimeout('post1001.submit();', 30000); }
{ post1001.submit(); setTimeout('post1002.submit();', 60000); }
...
{ post5092.submit(); setTimeout('post5093.submit();', 122790000); }
}, false);
You can also try something like this;
setTimeout(yourSubmitFunction, 3000)
function yourSubmitFunction() {
//do whatever you want to do you can define submit here
}
You can call setTimeout in a loop, like for each element in your array which has your "post****" variables.
I believe you shouln't use a string as first parameter for setTimeout();
Here is this function definition :
setTimeout(function,milliseconds,param1,param2,...)
Try with this code sample, or update yours accordingly :
setTimeout(function(){ alert("Hello"); }, 3000);
if i do:
method();
method();
both calls will run in parallel (at same time)
i just would like to make the second method(); wait until the first method(); is finished before to start, and do it dynamically cause i can't know how many times i will launch method(); at same time .
Is it possible?
just for example, those runs at same time as i can see... http://jsfiddle.net/Lcgb8/
You could use then if you return a Deferred.
E.g.
function method() {
var d = $.Deferred();
//do something async
setTimeout(function () {
d.resolve('some data'); //inform listeners that the process is completed
}, 2000);
return d; //return the deferred object
}
Then you could do:
method().then(method).then(method).then(method);
Note that the return value of each call will be passed as first argument to the next call, respectively.
EDIT: Here's an example on how you could queue the async operations dynamically.
FIDDLE
function changeColorAsync(color) {
var d = $.Deferred();
setTimeout(function () {
$('body').css('background', color);
d.resolve();
}, 4000);
return d;
}
$(function () {
$('#color-form').on('submit', function (e) {
var color = $(this).find(':checked').val(), d;
d = d?
d.then(changeColorAsync.bind(this, color)) :
changeColorAsync(color);
return false;
});
});
Here is a sequentially animation using transitionend
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>animation</title>
<style>
div{
width:50px;height:50px;background-color:#093;
-webkit-transition:all 300ms ease;
}
div.move{-webkit-transform:translate3d(200px,0,0);}/*GPU HW acceleration*/
</style>
<script>
(function(W){
var D,d,L,c=0;
function init(){
D=W.document;d=D.getElementsByTagName('div');L=d.length;var l=d.length;
while(l--){d[l].addEventListener('transitionend',next,false)}
next();
}
function next(){
d[c].classList[(d[c].className=='move'?'remove':'add')]('move');
c++;c=(c==L?0:c);
}
W.addEventListener('load',init,false);
})(window)
</script>
</head>
<body><div></div><div></div><div></div><div></div></body>
</html>
it had little error fixed now..
supports infinite div's and it's infinite loop using low resources. =)
your method() would be my next()
if someone want's to jsfiddle it... i don't use that.
ps.: pure javascript (no jquery) + css3 (with -webkit prefix);
example
http://jsfiddle.net/4eujG/
Have a look at jQuery.queue().
Using callback:
var test = function (letter, callback) {
console.log(letter);
if (typeof callback !== 'undefined') {
callback();
}
};
Now you can run it:
test('a', function () {
test('b', function () {
test('c')
});
});
The result in console is:
a
b
c
Is it helpful to you?
$( "div" ).promise().done(function() {
$( "p" ).append( " Finished! " );
});
Hope this example must have cleared your query
LIVE DEMO
Javascript, and most other languages, run code sequentially.
Therefore, they will not both run at the same time.
In fact, it is not possible to run two different pieces of Javascript code at the same time. However, in many other languages, it is possible using threads.
However, if they make AJAX calls, the corresponding server-side code called by both functions will run simultaneously.
To prevent that, you'll need to make the first function accept a callback parameter and pass it the second function.
I building website using following script. Sometime this javascript crash sometimes not. Weird thing is when I add alert box at third line after sliderLeft define, script never crash. Someone please help with this.
I am using same function twice for different output.
Even I remove Second similar function I am still getting error. Please help me with this.
$(window).load(function() {
var sliderLeft=$('#thumbScroller .container').position();
//alert(sliderLeft);
// padding=$('#outer_container').css('paddingRight').replace("px", "");
var sliderWidth=$(window).width()
$('#thumbScroller').css('width',sliderWidth);
var totalContent=0;
$('#thumbScroller .content').each(function () {
totalContent+=$(this).innerWidth();
$('#thumbScroller .container').css('width',totalContent);
});
//alert(sliderLeft);
$('#thumbScroller').mousemove(function(e){
if($('#thumbScroller .container').width()>sliderWidth){
var mouseCoords=(e.pageX - this.offsetLeft);
var mousePercentX=mouseCoords/sliderWidth;
var destX=-(((totalContent-(sliderWidth))-sliderWidth)*(mousePercentX));
var thePosA=mouseCoords-destX;
var thePosB=destX-mouseCoords;
var animSpeed=600; //ease amount
var easeType='easeOutCirc';
if(mouseCoords==destX){
$('#thumbScroller .container').stop();
}
else if(mouseCoords>destX){
//$('#thumbScroller .container').css('left',-thePosA); //without easing
$('#thumbScroller .container').stop().animate({left: -thePosA}, animSpeed,easeType); //with easing
}
else if(mouseCoords<destX){
//$('#thumbScroller .container').css('left',thePosB); //without easing
$('#thumbScroller .container').stop().animate({left: thePosB}, animSpeed,easeType); //with easing
}
}
});
$('#thumbScroller .thumb').each(function () {
$(this).fadeTo(fadeSpeed, 0.6);
});
var fadeSpeed=200;
$('#thumbScroller .thumb').hover(
function(){ //mouse over
$(this).fadeTo(fadeSpeed, 1);
},
function(){ //mouse out
$(this).fadeTo(fadeSpeed, 0.6);
}
);
});
$(window).resize(function() {
//$('#thumbScroller .container').css('left',sliderLeft); //without easing
$('#thumbScroller .container').stop().animate({left: sliderLeft}, 400,'easeOutCirc'); //with easing
$('#thumbScroller').css('width',$(window).width());
sliderWidth=$(window).width();
});
I just remove second function as per suggestion, but still not work
removed few lines and script crash and doesn't display any error
You have 2 $(window).load(function() {...}); function definitions.
Try combing them into 1 $(window).load(function() {...}); call.
Just an idea...
Hard to say without seeing the problem (as said by 3dgoo try put your code into jsfiddle.net) but Are you sure your code executes when dom is ready ?
It'd explained that the 'alert' you put in your code 'solve' the problem by giving it time to finish loading.
function jsFunc() {
alert('i am js!');
}
$('#node').slideDown().call(jsFunc());
Of course, the function isn't called 'call'.
** EDIT **
(Added solution on behalf of the OP).
Solution
http://jsfiddle.net/gx2mJ/1/
or
HTML:
<div id="content">
<p class="article">
this is an article
</p>
</div>
JavaScript:
function callBack() {
$("#content .article").html("the callback has been called");
}
$(document).ready(function() {
$("#content .article").slideUp(0);
$("#content .article").each(function(i) {
$(this).delay(i*250).slideDown(function(){
//if ($("#content .article:animated").length < 1) {
callBack();
//}
});
});
});
You can't do that by default, but you could easily add it as a plugin:
$.fn.call = function (fn, args, thisp) {
fn.apply(thisp || this, args);
return this; // if you want to maintain chainability -- other wise, you can move the return up one line..
}
Though I'm not sure why you would want to do that. If you're thinking it won't be run until after the slide is done, then you'd be wrong because jQuery animations are asynchronous.
why not just use a callback function? almost all jquery functions have them.
$('#node').slidedown('normal', function(){jsFunc()})
$("#content article").each(function(i) {
$(this).delay(i*250).slideDown();
}).callBack();
The whole reason for having the callback in the chain is so it will run AFTER all the animations have taken place.
try this instead,
$("#content .article").each(function(i) {
$(this).delay(i*250).slideDown(function(){
if ($("#content .article:animated").length < 1) {
callBack();
}
});
});
the same problem
What is your objective of calling the jsFunc()?
If you want it as a callback you can use the sysntax given here
ex:
$('#node').slidedown('normal', function(){jsFunc()}).
But if you want the function jsFunc to be able to call as a plugin, you need to write a plugin as suggested by CD Sanchez.
I think again there is one issue in your sample code, you are calling the function jsFunc and passing the value returned by jsFunc as an argument to the call function. If you want to pass the function jsFunc as the callback function you need to use the syntax
$('#node').slideDown().call(jsFunc);
(Added solution on behalf of the OP).
Solution
http://jsfiddle.net/gx2mJ/1/
or
HTML:
<div id="content">
<p class="article">
this is an article
</p>
</div>
JavaScript:
function callBack() {
$("#content .article").html("the callback has been called");
}
$(document).ready(function() {
$("#content .article").slideUp(0);
$("#content .article").each(function(i) {
$(this).delay(i*250).slideDown(function(){
//if ($("#content .article:animated").length < 1) {
callBack();
//}
});
});
});
$("#content article").each(function(i) {
$(this).delay(i*250).slideDown();
}).callBack();
The whole reason for having the callback in the chain is so it will run AFTER all the animation triggers have taken place.