I am facing an issue in my vue component where I need to add a fixed class to an element when the user scrolls past it. However, the sticky console.log seems to be firing on every scroll instead of only when the element is passed. I also want to remove the class when the element is not passed by.
Below is my component with jQuery code:
<template>
<div id="sticky" style="width:35%; height:85vh; padding:0px 0px; margin:0px 0px 0px auto; background-color:rgb(10,10,10); display:flex; flex-direction:column; position:relative; border:5px solid #9d0000; overflow:hidden; outline:2px solid red;">
</div>
</div>
</template>
<!--SCRIPTS-->
<script>
import $ from 'jquery';
export default {
name: 'CARTmodal2',
mounted() {
console.log(this.$options.name+' component successfully mounted');
let sticky = $('#sticky'),
stickyTop = sticky.offset().top,
scrolled = false,
$window = $(window);
/* Bind the scroll Event */
$window.on('scroll', function(e) {
scrolled = true;
});
let timeout = setInterval(function() {
/* If the page was scrolled, handle the scroll */
if (scrolled) {
scrolled = false;
if ($window.scrollTop() >= stickyTop) {
sticky.addClass('fixed');
console.log("sticky");
}
else {
sticky.removeClass('fixed');
}
}
}, 200);
},
};
</script>
<style scoped>
.fixed{position:fixed; top:0px; left:0px; border:1px slid black;}
</style>
Can anyone point out what might be the problem here?