Question

I'm creating a jquery script to vertically pan an image inside its container according to the cursor position.

This is what I've done :

        $(window).load(function(){
            var lastcalc = 0;
            $(".tn3a-image").mousemove(function(e){
              //var y = e.pageY-$(".tn3a-image").offset().top;
              //var Cnt_h = $(".tn3a-image").height();
              //var Cy = ($(".pan-view").height()-Cnt_h)/Cnt_h;
              var calc = -(($(".pan-view").height()/$(".tn3a-image").height())-1)*(e.pageY-$(".tn3a-image").offset().top)
              if (Math.abs(lastcalc-calc)<=1) return; 
              lastcalc = calc;
              $(".tn3a-full-image").stop(true,true)
                   .animate({ top : calc }, 500, 'linear');
            });
        });

It works as expected but the performances are really bad. It looks really sluggish, although I have a good GPU/CPU. I came up with two solutions - get the calculations made in a single variable (named 'calc'), and use '.stop(true,true)'. Yet I'm still not really satisfied with it. It looks really bad compared to Flash-based solutions.

Any ideas on how to optimize this ?

Thanks for your help.

Was it helpful?

Solution

Here is a simple way to throttle your handler:

var IsPanning = false;
$(window).load(function(){
            var lastcalc = 0;
            $(".tn3a-image").mousemove(function(e){
              if(IsPanning == false){

                  IsPanning= true;
                  var calc = -(($(".pan-view").height()/$(".tn3a-image").height())-1)*(e.pageY-$(".tn3a-image").offset().top)
                  if (Math.abs(lastcalc-calc)<=1) return; 
                  lastcalc = calc;
                  $(".tn3a-full-image").stop(true,true)
                     .animate({ top : calc }, 500, 'linear');
                  });
                  IsPanning = false;
               }
           });

Sorry, I can't check to see if there are any syntax errors at the moment, hopefully it gives you the idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top