Reputation: 135
I'm a superbeginner at JQuery but I really like to play with it. I was making a page and it started to get slow/glitchy and I don't how to use callbacks yet and I think it would help a lot.
The code I'm using looks like this:
$(".navHome").click(function(){
var div=$(".navHome");
div.animate({left:'190px'},"fast");
var div=$(".content");
div.animate({width:'700px'},"slow");
div.animate({height:'250px'},"slow");
$(".content").load("home.html");
var div=$(".xIcon");
div.animate({width:'20px'},"slow");
div.animate({height:'20px'},"slow");
});
So I click on a div "navHome", it moves and the "content" div expands/loads. But its starting to look choppy. I think callbacks are what I need but am not sure.
Upvotes: 4
Views: 260
Reputation: 144659
You should not define a variable multiple times in the same scope, this is your code using callback functions, note that you can animate multiple properties using one animate method.
.animate( properties [, duration] [, easing] [, complete] )
$(".navHome").click(function(event){
// event.preventDefault(); // prevents the default action of the event
$(this).animate({left:'190px'},"fast", function(){
$(".content").animate({width:'700px', height:'250px'},"slow", function(){
$(this).load("home.html", function(){
$(".xIcon").animate({width:'20px', height:'20px'},"slow");
})
})
});
});
Upvotes: 6
Reputation: 16961
Callbacks probably aren't what you want, as your animation would "queue", having one after the other.
It's probably getting choppy because you've got too much going on... javascript css animation isn't particularly fast, and is largely browser dependent because of the differences in javascript engines. If you're looking for smoother animation, I'd suggest adding and removing classes which have CSS transitions applied, as CSS is hardware accelerated and doesn't take up precious javascript resource, allowing the rest of your application to run a lot smoother.
As a side note, you don't need to redeclare div
each time using the var
keyword, and you can also animate multiple properties by comma separating your object properties and chain your jQuery methods so you don't have to re-query the DOM, like this:
$(".navHome").click(function(){
$(this).animate({left:'190px'},"fast");
$(".content").animate({width:'700px', height:'250px'},"slow")
.load("home.html");
$(".xIcon").animate({width:'20px', height:'20px'},"slow");
});
Upvotes: 1
Reputation: 829
Try this:
$(".navHome").click(function(){
$(this).animate({left:'190px'},"fast");
$(".content")
.animate({width:'700px'},"slow");
.animate({height:'250px'},"slow");
$(this).load("home.html");
$(".xIcon")
.animate({width:'20px'},"slow");
.animate({height:'20px'},"slow");
});
Look at the syntax - you should refacter your code and make it easier!
Upvotes: 0