jquery, control order of how code is executed - javascript

Via PHP, i'm generating some JavaScript code, witch looks like this:
<script type="text/javascript">
$(window).load(function() {
maps.showUsers('Odenthal, Germany',1);
maps.putCenter(51.1833,7.2);
});
</script>
I have to be sure, that the first line is executed before the second line. This works fine in IE and FF, but not in Chrome. How can i control it?

try callbacks:
$(window).load(function() {
maps.showUsers('Odenthal, Germany',1, function(){
maps.putCenter(51.1833,7.2);
});
});
you have to use that callback at the end of your function:
function showUsers(a, b, c, callback) {
...
if(typeof callback == 'function')
callback.call();
}

Try this with some delay. You can set the appropriate delay as per your need.
$(window).load(function() {
maps.showUsers('Odenthal, Germany',1);
setTimeout(function(){
maps.putCenter(51.1833,7.2);
}, 400);
});

Related

Changing modal content breaks AJAX events

I use jquery-ujs for ajax requests (data-remote="true"). My problem is, that the first request is okay, and while the second is running, it breaks. Whenever I call in the events $('#modal').empty() or $('#modal').text('') or $('#modal').html(''), no more events are going to be called.
To be clear, here's the code:
$(document).on('ajax:beforeSend', function () {
console.log('beforeSend');
$('#modal').empty().modal('show');
});
$(document).on('ajax:send', function () {
console.log('send');
});
$(document).on('ajax:success', function (e, xhr) {
console.log('success');
$('#modal').html(xhr).drags({ handle: '.modal-header' }).modal('show');
if (typeof doWork === 'function') {
doWork();
}
});
$(document).on('ajax:complete', function () {
console.log('complete');
});
And the console output:
beforeSend
send
success
complete
beforeSend
If I move $('#modal').empty().modal('show'); to the send event, then it is going to be called, but the success method is never called anymore (neither error neither complete, nothing more).
This problem annoys me for more hours now... Thank you for your help.
How about to move empty() to the ajax:complete?
In this case, when your modal closes, it opens empty for the next use and is ready for reuse.
I suggest that you put this command in the last step so that it does not cause any problems. Like the following:
$(document).on('ajax:complete', function () { console.log('complete'); . . . . $('#modal').empty(); });
I believe that this is not the best solution and there are definitely other solutions. But I hope this solution will solve your problem.
$('#modal').on('hidden.bs.modal', function () {
$(this).empty()
})
My workaround was to avoid using jquery-ujs events and using global ajax events, so my final working code is:
$(document).ajaxSend(function () {
$('#modal').empty().modal('show');
});
$(document).ajaxSuccess(function (e, xhr) {
$('#modal').html(xhr.responseText).drags({ handle: '.modal-header' }).modal('show');
if (typeof doWork === 'function') {
doWork();
}
});

jQuery .on('load') doesn't work with an object/iframe while .addEventListener('load') does

I'm trying to modify an iframe/object content adding a script into it. At the moment, I have something like this:
// "script" is a node with an self-called function as its content
$(function() {
$('object, iframe').each(function() {
this.addEventListener('load', function() {
this.contentDocument.getElementsByTagName('head')[0].appendChild(script.cloneNode(true));
});
});
});
And it works as expected (the script does its job and it is added to the DOM of the iframe) but the problem comes when I try to do it the "jQuery" way:
// "script" is a node with an self-called function as its content
$(function() {
$('object, iframe').each(function() {
$(this).on('load', function() {
this.contentDocument.getElementsByTagName('head')[0].appendChild(script.cloneNode(true));
});
});
});
In the previous code, the script won't be added to the dom of the iframe.
Is there any reason why the .on('load') version is not working? What can be wrong? Am I missing something?
PS: The iframe is same-origin.
In each case, the inner function's this might not always be what you want it to be. I'd try:
$(function() {
$('object, iframe').each(function () {
$(this).on('load', function (event) {
event.target.contentDocument.getElementsByTagName('head')[0].appendChild(script.cloneNode(true));
});
});
});
Cf. https://api.jquery.com/event.target/

jQuery - run multiple methods sequentially

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.

Javascript crash sometimes and sometimes not?

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.

Document.ready function

I have some code in the - $(document).ready(function(){ - that shuffles stuff around, the code is fired when the page is loaded but what I want to do is add a button so this function runs every time I press the button, how could I achieve this, thanks??
function shuffleStuffAround() {
// truffle shuffle
}
$(function($) { // DOM ready
shuffleStuffAround();
$("#some-button").click(function() {
shuffleStuffAround();
return false; // you probably want this
});
});
You can save you "shuffle stuff around" code as a function and call it from other parts of your codebase.
var foo = function() {
// code that shuffles stuff around
};
$(document).ready(function() {
foo();
// other stuff
});
$('#mybutton').click(foo);
//or
$('#mybutton').click(function() {
foo();
// other stuff.
});
You could simple refactor the code that you run on the ready function into its own function and call that in your button's click event:
$(document).ready(function(){
codeToRun();
$('.button').click(function(){codeToRun()});
});
function codeToRun(){
// do work
}

Categories

Resources