3

On a website i'm making at my internship, I want to make a arrow, that flattens once the user is scrolling down. I have tried to make this with jQuery, but this seemed to be very heavy for the browser.

For this function, I used the .scroll() function, and a calculation that makes the arrow (triangle) flatter once the user scrolls down:

$(window).scroll(function(e){
     triangleRotation = 5.6125 - ($(window).scrollTop() / ($(window).height() / 7.3));
       if (triangleRotation <= 0) {
        triangleRotation = 0;
       }
       $('.triangle-left').css({'transform': 'rotate(' + triangleRotation + 'deg)', '-webkit-transform': 'rotate(' + triangleRotation + 'deg)', '-moz-transform': 'rotate(' + triangleRotation + 'deg)'});
       $('.triangle-right').css({'transform': 'rotate(-' + triangleRotation + 'deg)', '-webkit-transform': 'rotate(-' + triangleRotation + 'deg)', '-moz-transform': 'rotate(-' + triangleRotation + 'deg)'});
});

I also tried this via a triangle shaped image, and simply flatten the image. This was also to heavy.

Is there a less heavy way to do this?

Maarten Wolfsen
  • 1,625
  • 3
  • 19
  • 35
  • I'd suggest always using css transforms, as this should only trigger paint, and not reflow or layout. - Also, make sure that you use a 'throttle' on the `onscroll` event function. – evolutionxbox Apr 20 '16 at 13:11
  • It was done via a css transform, I just posted the source code – Maarten Wolfsen Apr 20 '16 at 13:12
  • Maybe don't calculate `$(window).height() / 7.3` every time the scroll event is fired. - [Here is an example of a js throttle](http://benalman.com/projects/jquery-throttle-debounce-plugin/) – evolutionxbox Apr 20 '16 at 13:14
  • But, how am I supposed to rotate the triangles (and let the rotation stop if the user stops scrolling) – Maarten Wolfsen Apr 20 '16 at 13:15
  • Another suggestion, "cache" the triangle objects in variables outside the scroll function. Your code currently rotates the triangles on scroll, and the rotation also stops when the user stops scrolling... – evolutionxbox Apr 20 '16 at 13:19

1 Answers1

3

You could try to:

  • create a globally reachable variable 'is_scrolling' and set it to true in the scroll event (if it isn't true).
  • use the code from here to set the variable to false if the user stopped scrolling
  • Use a setTimeout to rotate. You can manage speed with the timeout time and the degrees per step (if rotation is independent of scroll position) otherwise use your calculation.

Advantage is, that this is decoupled from the scrolling event. You have no control over how often the scrolling event is triggered, but triggering of the function in setTimeout you CAN control.

Community
  • 1
  • 1
TehSphinX
  • 6,536
  • 1
  • 24
  • 34