I wanted to create a fixed progress bar in Vue that doesn't decrease when scrolling up. After searching for information without success, I decided to create an account on this website to share my solution.
First, it's important to note that Vue doesn't provide a built-in directive like v-on to listen for scrolling up. However, you can achieve this by using the @scroll
event listener, like this: @scroll="onScroll"
Next, create a scrollValue data property:
data: () => ({
scrollValue: 0,
}),
Now, let's implement the onScroll method:
methods: {
onScroll(e) {
let el = e.target;
this.scrollValue = Math.max(
this.scrollValue,
Math.ceil(el.scrollTop) / (el.scrollHeight - el.clientHeight)
);
},
},
I added the onScroll
method to handle the scroll event. Inside the method, we access the scroll position using el.scrollTop
and calculate the progress ratio by dividing it with the difference between the total scroll height and the visible height of the container.
Lastly, there might be some inconsistencies in different browsers with the el.scrollTop
value, which might not reach exactly 100%. To handle this, I used Math.ceil
to round up the value and ensure accurate progress tracking.
That's it! With this implementation, the progress bar should work as expected. I hope this solution helps you in your project.
Note: This is my first post, so please bear with me.
Top comments (4)
Try chatgpt, it will generate multiple code snippets for your progress bar which could be more efficient
What do you mean?
My article only talks about this function:
I just tried to find a solution and only got useless examples with lots of extra variables.
But maybe I didn't quite get you right
I meant with proper statement you can generate more efficient codes in ChatGPT and compare it with your own code, if you don't find any difference then your code is perfect else you might get better version of your code, it's not this example alone it's for Other codes as well
I got you. I used ChatGPT for this issue, but it also didn't helpðŸ«