Reputation: 133
I would like to make an effect of swiping images using jQuery. When I click an image, I want to 1) make the frame width to zero, 2) change to another image, and 3) make the frame width to 100% again. I used the following code, and whatever I do, the image changes first before the frame expands back to 100% (1-> 3-> 2). I tried use callback function, but could not figure it out. Any advice please?
$("#frame img").click(function(){
$("#frame").animate({width:"0%", height:"100%"}, "slow"); //1
$("#frame img").attr({src:"images2.png"}); //2
$("#frame").animate({width:"100%", height:"100%"}, "slow"); //3
});
The following is what I have tried with callback function (and I think it's completely wrong):
$("#frame img").click(function(){
$("#frame").animate(({width:"0%", height:"100%"}, "slow"), function(){
$("#frame img").attr(({src:"images2.png"}), function(){
$("#frame").animate({width:"100%", height:"100%"}, "slow");
});
)};
});
Upvotes: 3
Views: 765
Reputation: 13003
Try the following example and tell me if it's OK for you:
$('#clickme').click(function() {
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 5000, function() {
// Animation complete.
});
});
For full reference: http://api.jquery.com/animate/ and read about Complete Function
Upvotes: 0
Reputation: 1891
There's a couple of jQuery plugins that does what you're looking for... If I find it I'll comment back on this answer. For now here's how you can do it.
$("#frame img").click(function(){
$("#frame").animate({width:0}, "slow", function(){
$("#frame img").attr({src:"images2.png"}).ready(function(){
$("#frame").animate({width:$("#frame img").width()}, "slow");
});
});
});
.ready makes sure the image is loaded before reanimating.
Upvotes: 1
Reputation: 137300
Use callbacks (where possible, eg. .attr()
does not support callbacks):
$("#frame img").click(function(){
$("#frame").animate({width:"0%", height:"100%"}, "slow", function(){
// a callback executed, when the first animation completes
$("#frame img").attr({src:"images2.png"});
$("#frame").animate({width:"100%", height:"100%"}, "slow");
});
});
But your code can be optimized. One of the approaches may look like this:
var frame = $("#frame"); // cache frame
var images = frame.find("img"); // cache images within frame
images.click(function(){
frame.animate({width:"0%", height:"100%"}, "slow", function(){
// a callback executed, when the first animation completes
images.attr({src:"images2.png"});
frame.animate({width:"100%", height:"100%"}, "slow");
});
});
(unless of course the results of $("#frame")
and $("#frame img")
do not change over time)
Upvotes: 2