Monday 26 September 2011

JQuery jerky movements

Even some of the simplest jquery animations can have a disappointing jerky quality to them. After a bit of digging I found that sometimes when jquery is animating something it gets the height (and therefore the animation step-heights) wrong. This led me to look at a quick fix -

1) Dynamically get the height of the element with .height()
2) Set the css to the fixed pixel value with .css(property, value)

My example has a nav element filled with divs, which in turn may have an ul (sub menu) to display.

View the Demo


 
$("nav div").hover(
function() { // i.e. onmouseover function

/*simple lines to fix a % based height to a px based height*/
var h = jQuery(this).find("ul").height(); //find the height
jQuery(this).find("ul").css("height", h);
//set the css height value to this fixed value
/***********************************************************/

jQuery(this).find("ul").stop(false, true).slideDown("500");
},
function(){ // i.e. onmouseout function
jQuery(this).find("ul").stop(false, true).slideUp("500");
});
});


NB the stop(false,true) makes sure that if the user is playing with the controls the animations will continue smoothly but won't stack up to cause an issue.

No comments:

Post a Comment