jquery - How to create a "Simple Harmonic Oscillation" on scroll event using Javascript -
currently have element on page. object oscillate left , right similar 1 in example give below. however, bind oscillation browser window scroll event.
https://www.khanacademy.org/computer-programming/simple-harmonic-motion/4920589909229568
i tried it's not smooth , accurate:
javascript
let butterfly_y_position_log = []; let scroll_times = 0; let scroll_direction; $(window).scroll(function(){ let butterfly_y_position = $('.floating-butterfly').offset().top; let butterfly_x_position; butterfly_y_position_log.push(butterfly_y_position); if (butterfly_y_position_log.length > 2){ butterfly_y_position_log = butterfly_y_position_log.slice(1, 4); } if (butterfly_y_position_log[0] < butterfly_y_position_log[1] || butterfly_y_position_log[1] == undefined){ scroll_direction = 'down'; scroll_times++; butterfly_x_position = ($(window).width() / 2) + (100 * math.sin(2* math.pi + scroll_times)); } else { scroll_direction = 'up'; scroll_times--; butterfly_x_position = ($(window).width() / 2) + (100 * math.cos(2* math.pi + scroll_times)); } console.log(scroll_times); console.log(butterfly_x_position); $('.floating-butterfly').css({left:butterfly_x_position}); }); html
<img src="..." class="floating-butterfly"> css
.floating-butterfly { position: fixed; top: 40px; z-index: 2; } the y-position remain fixed, x-position change on scroll.

Comments
Post a Comment