javascript - Moving Element according to vertical Scroll - most performant way? -
i'm building little script manipulate elements according vertical page-scrolling. solution works fine, i'm wondering if there more performant way this. love keep smooth , fluent.
$(document).ready(function(){ var element = $("#element1"); var elementoffset = element.offset().top; var windowheight = $(window).height(); var distanceentry = windowheight*0.8; // distance element var distanceexit = windowheight*0.2; // distance element var entry = elementoffset-distanceentry; // entry point in px pagetop var exit = elementoffset-distanceexit; // exit point in px pagetop var stepping = (exit-entry)/100; // px percentage $("#entry").css("top", entry); // placing entry-marker $("#exit").css("top", exit); // placing exit-marker $(window).scroll(function(){ var scroll = $(window).scrolltop(); var value = (scroll-entry)/stepping; // calculation progress of animation if(value>=100) {value=100;} // cutting top , bottom if(value<=0) {value=0;} // cutting top , bottom value = math.round(value); // integer $("#element1").css("left", value); // writing value element $("#head").html("element-movement in percent: " + value); }); });
thank you!
since scroll
event fires often, might see slight improvements in performance if move logic out of scroll event possible.
in example of element selection moved out of listener, , if statements don't need >=
, <=
. <
, >
achieve same thing. e.g.
var $win = $(window); var $element1 = $("#element1"); var $head = $("#head"); $win.scroll(function(){ var scroll = $win.scrolltop(); var value = (scroll-entry)/stepping; // calculation progress of animation if(value>100) {value=100;} // cutting top , bottom if(value<0) {value=0;} // cutting top , bottom value = math.round(value); // integer $element1.css("left", value); // writing value element $head.html("element-movement in percent: " + value); });
not sure give noticable perf gains, shouldn't hurt.
Comments
Post a Comment