How to use callbacks in jQuery?

I am a super-runner in jQuery, but I really enjoy playing with him. I was making a page and it was starting to slow down / buggy, and I don't use callbacks, and I think it helped a lot.

The code I use is as follows:

$(".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 the “navHome” div, it moves, and the “content” div expands / loads. But his start to look messy. I think callbacks are what I need, but I'm not sure.

+4
source share
3 answers

You do not have to define the variable several times in the same area, this is your code using callback functions, note that you can animate several properties using one animation 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"); }) }) }); }); 
+6
source

Callbacks are probably not what you want, since your animation will be "queued", having one after the other.

This probably becomes volatile because you go on too much ... javascript css animation is not particularly fast and heavily browser dependent due to differences in javascript machines. If you are looking for smoother animations, I would suggest adding and removing classes that use CSS transitions, since CSS is hardware accelerated and does not take up the precious javascript resource, allowing the rest of your application to run much smoother.

As a side note, you don’t need to update the div every time using the var keyword, and you can animate several properties by comma, separating your object properties and binding your jQuery methods so you don’t need to re-query the DOM, for example:

 $(".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"); }); 
+1
source

Try the following:

 $(".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 have to update your code and make it easier!

0
source

Source: https://habr.com/ru/post/1447591/


All Articles