// EDIT: Cache the text elements. This is very time consuming. var texts = $('[data-type="scroll-text"]', $self); // EDIT: Also a bit faster than querying the DOM each time. var speed = $self.data('speed'); var offset_y = $self.data('offsetY'); // When the window is scrolled... $(window).scroll(function () { // EDIT: Cache the scroll top. Much cleaner and a bit faster. // You want to optimize scroll listeners as much as possible. var scroll_top = $window.scrollTop(); // If this section is in view if (scroll_top + $window.height() > topOffset && topOffset + $self.height() > scroll_top) { // Scroll the background at var speed // the yPos is a negative value because we're scrolling it UP! var yPos = -(scroll_top / speed); // If this element has a Y offset then add it on if (offset_y) { yPos += offset_y; } // Put together our final background position var coords = '50% '+ yPos + 'px'; // Move the background $self.css({ backgroundPosition: coords }); texts.each(function() { var $text = $(this); var pos = (scroll_top / 10) * $text.data('speed'); $text.css('margin-top', pos); }); }; // in view }); // window scroll