Jquery Animations not waiting for callback - javascript

I have a Jquery animation that is running the code from its function before the animation is complete. the Page this code is being used at is no where near complete yet but if you want to take a look it's cottageboards.com/orderform
$('#snow').fadeIn(500, "linear", function () {
$('#largeImage').fadeOut(500, function () {
$('#largeImage').attr('src', selectedimg).load(function () {
$('#largeImage').fadeIn(1000, function () {
//Everything below here is running before the above image's fade in is complete
$('#snow').fadeOut(5000);
var selection = 'input[name="' + $(selectionage).data('type') + '_selection"]';
$($('#selected_thumb').val()).attr('src', $($('#selected_thumb').val()).data('regular'));
$(selectionage).attr('src', $(selectionage).data('selected'));
selectedid = '#' + $(selectionage).attr('id');
$('#selected_thumb').val(selectedid);
$('#selected_info').html($(selectionage).data('desc'));
$('#name').html($(selectionage).data('name'));
if ($(selectionage).data('val') === 99) {
$('#upload').show();
$('#displayinfo').hide();
} else {
$(selection).val($(selectionage).data('val'));
$('#upload').hide();
$('#displayinfo').show();
}
$('#next').prop('disabled', false);
});
});
});
});
When rewritten so the load function comes before the src change it works like a charm. Thanks for the help guys!
Working code:
$('#snow').fadeIn(500, "linear", function () {
$('#largeImage').fadeOut(500, function () {
$('#largeImage').unbind().load(function () {
$('#largeImage').fadeIn(1000, function () {
$('#snow').fadeOut(5000);
var selection = 'input[name="' + $(selectionage).data('type') + '_selection"]';
$($('#selected_thumb').val()).attr('src', $($('#selected_thumb').val()).data('regular'));
$(selectionage).attr('src', $(selectionage).data('selected'));
selectedid = '#' + $(selectionage).attr('id');
$('#selected_thumb').val(selectedid);
$('#selected_info').html($(selectionage).data('desc'));
$('#name').html($(selectionage).data('name'));
if ($(selectionage).data('val') === 99) {
$('#upload').show();
$('#displayinfo').hide();
} else {
$(selection).val($(selectionage).data('val'));
$('#upload').hide();
$('#displayinfo').show();
}
$('#next').prop('disabled', false);
});
}).attr('src', selectedimg);
});
});

You are binding the load function to largeimage every time you click. The first click the load function gets called once, the second time, it gets called twice. I suspect everything is getting messed up because you are firing multiple .fadeIns on the same object, and they are running in parallel.
Only call $('#largeImage').load(...) once, not on every click. Of course, you'll have to do something about your captured vars, but that's a different issue. Alternatively, call $('#largeImage').unbind().load(...)
If that's hard to follow, replace this line:
$('#largeImage').attr('src', selectedimg).load(function () {
with:
$('#largeImage').unbind().attr('src', selectedimg).load(function () {
I tested it by putting a break point after this line:
$('#thumbs').delegate('img','click', function() {
and calling $('#largeImage').unbind(); and everything seemed to work, so you can do it that way too.

see this fiddle for example how to use done : http://jsfiddle.net/gcnes8b2/1/
$('span').click(function() {
$('#1').fadeIn({
duration: 1000,
done:function(){
$('#2').fadeOut(1000);
// etc
}
});
});

Related

JQuery: Onload event on image not working

I am trying to call a function after the image loads completely in DOM.
The image structure is created dynamically on AJAX call success and the image url is also added in success using the result of API call.
Problem:
I want to call a function after the image loads completely in DOM.
To do this I have used JQuery load event.
Function which is called on load.
function carouselHeight() {
$('.home-banner-img-container').each(function() {
var $this = $(this);
var dynamicheight = $(this).parent();
var sectionInnerHeight = $this.innerHeight();
dynamicheight.css({
'height': sectionInnerHeight
});
});
}
I have tried below steps but it didn't worked
$(window).on('load', function() {
carouselHeight();
});
$(window).on('load', 'img.image-preview', function() {
carouselHeight();
});
$(document).on('load', 'img.image-preview', function() {
carouselHeight();
});
The first method $(window).on('load', function() {}) works perfectly on hard reload but on normal reload it is not able to find $('.home-banner-img-container') element which is inside of carouselHeight function.
Please help me to find a solution for this. Thank you.
I have found the solution on stack overflow where I have added the below code in ajax call complete method.
function imageLoaded() {
// function to invoke for loaded image
// decrement the counter
counter--;
if( counter === 0 ) {
// counter is 0 which means the last
// one loaded, so do something else
}
}
var images = $('img');
var counter = images.length; // initialize the counter
images.each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});

How to pass variable asyncronously through different scripts

I can't figure out how to do it.
I have two separate scripts. The first one generates an interval (or a timeout) to run a specified function every x seconds, i.e. reload the page.
The other script contains actions for a button to control (pause/play) this interval.
The pitfall here is that both sides must be asyncronous (both run when the document is loaded).
How could I properly use the interval within the second script?
Here's the jsFiddle: http://jsfiddle.net/hm2d6d6L/4/
And here's the code for a quick view:
var interval;
// main script
(function($){
$(function(){
var reload = function() {
console.log('reloading...');
};
// Create interval here to run reload() every time
});
})(jQuery);
// Another script, available for specific users
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
$icon = $playerButton.children('i');
buttonAction = function(e){
e.preventDefault();
if ($(this).hasClass('playing')) {
// Pause/clear interval here
$(this).removeClass('playing').addClass('paused');
$icon.removeClass('glyphicon-pause').addClass('glyphicon-play');
}
else {
// Play/recreate interval here
$(this).removeClass('paused').addClass('playing');
$icon.removeClass('glyphicon-play').addClass('glyphicon-pause');
}
},
buttonInit = function() {
$playerButton.on('click', buttonAction);
};
buttonInit();
});
})(jQuery);
You could just create a simple event bus. This is pretty easy to create with jQuery, since you already have it in there:
// somewhere globally accessible (script 1 works fine)
var bus = $({});
// script 1
setInterval(function() {
reload();
bus.trigger('reload');
}, 1000);
// script 2
bus.on('reload', function() {
// there was a reload in script 1, yay!
});
I've found a solution. I'm sure it's not the best one, but it works.
As you pointed out, I eventually needed at least one global variable to act as a join between both scripts, and the use of a closure to overcome asyncronous issues. Note that I manipulate the button within reload, just to remark that sometimes it's not as easy as moving code outside in the global namespace:
Check it out here in jsFiddle: yay! this works!
And here's the code:
var intervalControl;
// main script
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
reload = function() {
console.log('reloading...');
$playerButton.css('top', parseInt($playerButton.css('top')) + 1);
};
var interval = function(callback) {
var timer,
playing = false;
this.play = function() {
if (! playing) {
timer = setInterval(callback, 2000);
playing = true;
}
};
this.pause = function() {
if (playing) {
clearInterval(timer);
playing = false;
}
};
this.play();
return this;
};
intervalControl = function() {
var timer = interval(reload);
return {
play: function() {
timer.play();
},
pause: function(){
timer.pause();
}
}
}
});
})(jQuery);
// Another script, available for specific users
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
$icon = $playerButton.children('i'),
interval;
buttonAction = function(e){
e.preventDefault();
if ($(this).hasClass('playing')) {
interval.pause();
$(this).removeClass('playing').addClass('paused');
$icon.removeClass('glyphicon-pause').addClass('glyphicon-play');
}
else {
interval.play();
$(this).removeClass('paused').addClass('playing');
$icon.removeClass('glyphicon-play').addClass('glyphicon-pause');
}
},
buttonInit = function() {
$playerButton.on('click', buttonAction);
interval = intervalControl();
};
buttonInit();
});
})(jQuery);
Any better suggestion is most welcome.

Issue with a resize function after ajax refresh

Im having issues with combining 2 scripts
I have javascript code that checks how big my container is and if its bigger than 500 it devides the content into 2 different divs:
function divideStream() {
if ($("#stream_one_col").width() > 500) {
var leftHeight = 0;
var rightHeight = 0;
$("#stream_one_col").children().each(function() {
if (rightHeight < leftHeight) {
$("#stream_right_col").append(this);
rightHeight += $(this).height();
$(this).children().addClass("stream_right_inner");
}
else {
$("#stream_left_col").append(this);
leftHeight += $(this).height();
$(this).children().addClass("stream_left_inner");
}
});
}
else {
$("#content_left").load("php/stream_left.php");
}
}
And I have an ajax refresh
$(document).ready(
function() {
setInterval(function() {
$('.aroundit').load('php/stream_left.php');
$(".aroundit").divideStream();
}, 3000);
});
Now basically the reloading goes just fine
However, the function (divideStream) wont reload after the ajax is activated
Instead it just keeps jumping back and forth
Can anyone help me?
the function divideStream is not a extend function of jQuery .
You should use this:
$(document).ready(
function() {
setInterval(function() {
$('.aroundit').load('php/stream_left.php');
divideStream();
}, 3000);
});
I'm not quite sure I understand what is happening. But I think you might want to make sure that you run your divideSteam function after the load has completed. You can do it like this.
$(document).ready(
function() {
setInterval(function() {
$('.aroundit').load('php/stream_left.php', function() { //this function runs once load has completed
divideStream(); // as hugo mentioned
});
}, 3000);
});

does jQuery stop() work on custom functions?

There are three images that I have made a tooltip for each.
I wanted to show tooltips within timed intervals say for 2 seconds first tooltip shows and for the second interval the 2nd tooltips fades in and so on.
for example it can be done with this function
function cycle(id) {
var nextId = (id == "block1") ? "block2": "block1";
$("#" + id)
.delay(shortIntervalTime)
.fadeIn(500)
.delay(longIntervalTime)
.fadeOut(500, function() {cycle(nextId)});
}
now what i want is to stop the cycle function when moseover action occurs on each of the images and show the corresponding tooltip. And again when the mouse went away again the cycle function fires.
If I understand everthing correctly, than try this code. Tt stops the proccess if you hover the image and continues if you leave the image. The stop() function will work on custom functions if you implement them like the fadeOut(), slideIn(), ... functions of jquery.
$('#' + id)
.fadeIn(500, function () {
var img = $(this).find('img'),
self = $(this),
fadeOut = true;
img.hover(function () {
fadeOut = false;
},
function () {
window.setTimeout(function () {
self.fadeOut(500);
}, 2000);
}
);
window.setTimeout(function () {
if (fadeOut === false) {
return;
}
self.fadeOut(500);
}, 2000);
});​

jQuery function attr() doesn't always update img src attribute

Context: On my product website I have a link for a Java webstart application (in several locations).
My goal: prevent users from double-clicking, i. e. only "fire" on first click, wait 3 secs before enabling the link again. On clicking, change the link image to something that signifies that the application is launching.
My solution works, except the image doesn't update reliably after clicking. The commented out debug output gives me the right content and the mouseover callbacks work correctly, too.
See it running here: http://www.auctober.de/beta/ (click the Button "jetzt starten").
BTW: if anybody has a better way of calling a function with a delay than that dummy-animate, let me know.
JavaScript:
<script type="text/javascript">
<!--
allowClick = true;
linkElements = "a[href='http://www.auctober.de/beta/?startjnlp=true&rand=1249026819']";
$(document).ready(function() {
$('#jnlpLink').mouseover(function() {
if ( allowClick ) {
setImage('images/jetzt_starten2.gif');
}
});
$('#jnlpLink').mouseout(function() {
if ( allowClick ) {
setImage('images/jetzt_starten.gif');
}
});
$(linkElements).click(function(evt) {
if ( ! allowClick ) {
evt.preventDefault();
}
else {
setAllowClick(false);
var altContent = $('#jnlpLink').attr('altContent');
var oldContent = $('#launchImg').attr('src');
setImage(altContent);
$(this).animate({opacity: 1.0}, 3000, "", function() {
setAllowClick(true);
setImage(oldContent);
});
}
});
});
function setAllowClick(flag) {
allowClick = flag;
}
function setImage(imgSrc) {
//$('#debug').html("img:"+imgSrc);
$('#launchImg').attr('src', imgSrc);
}
//-->
</script>
A delay can be achieved with the setTimeout function
setTimeout(function() { alert('something')}, 3000);//3 secs
And for your src problem, try:
$('#launchImg')[0].src = imgSrc;
Check out the BlockUI plug-in. Sounds like it could be what you're looking for.
You'll find a nice demo here.
...or just use:
$(this).animate({opacity: '1'}, 1000);
wherever you want in your code, where $(this) is something that is already at opacity=1...which means everything seemingly pauses for one second. I use this all the time.
Add this variable at the top of your script:
var timer;
Implement this function:
function setFlagAndImage(flag) {
setAllowClick(flag);
setImage();
}
And then replace the dummy animation with:
timer = window.setTimeout(function() { setFlagAndImage(true); }, 3000);
If something else then happens and you want to stop the timer, you can just call:
window.clearTimeout(timer);

Categories