Implement Click-to-Scroll to Current User Position in a Vue3 Ranking List
This tutorial explains how to use Vue 3 to render a ranking list, add a unique data-key to each user item, and implement a click handler that smoothly scrolls the selected user into view with Element.scrollIntoView while optionally highlighting the element for two seconds.
Requirement: When a user clicks on a div representing the current user in a ranking list, the page should automatically scroll the element into view.
Implementation uses Vue 3 with a v-for loop to render the list, adding a custom data-key attribute (the user_id ) to each item.
Key template code:
<div v-for="(item, index) in rankingData" :key="item.user.id" :data-key="item.user.id"></div>The click handler receives the userId and performs three steps:
Obtain the ranking list DOM via a ref, e.g., const rankingList = ref(null) .
Find the target element with rankingList.value.querySelector(`[data-key="${id}"]`) .
Call currentItem.scrollIntoView({ behavior: 'smooth', block: 'center' }) to smoothly center the element.
The article also explains the three overloads of Element.scrollIntoView() and its options such as behavior , block , and inline .
To improve usability, additional code highlights the selected element for two seconds using two helper functions:
const applyHighlightStyles = (element) => {
element.style.transition = 'background-color 1s ease, border-color 1s ease';
element.style.border = '1px solid transparent';
element.style.borderColor = '#006cfe';
element.style.backgroundColor = '#cfe5ff';
};
const removeHighlightStyles = (element) => {
element.style.backgroundColor = '';
element.style.borderColor = 'transparent';
};After scrolling, the handler calls applyHighlightStyles(currentItem) , sets a timeout to invoke removeHighlightStyles after 2000 ms, and clears any existing timers. The component’s onUnmounted hook also clears timers for all items.
The final result is a smooth scroll to the selected user’s position with a temporary highlight, as demonstrated by the included GIFs.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.