Created
February 6, 2025 12:00
-
-
Save themodernpk/0525e32abb417cfb0d86bc7aa6fb4737 to your computer and use it in GitHub Desktop.
Position on Scroll
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<div class="spacer">Scroll Down</div> | |
<div data-testid="test-item" class="target-item"> | |
Target Element | |
</div> | |
<div class="spacer">Keep Scrolling</div> | |
</div> | |
</template> | |
<script setup> | |
import { onMounted, onUnmounted } from 'vue'; | |
let targetElement = null; | |
const updatePosition = () => { | |
if (targetElement) { | |
const rect = targetElement.getBoundingClientRect(); | |
const positionFromTop = rect.top + window.scrollY; // Position from the top of the page | |
console.log('Position from top:', positionFromTop); | |
} | |
}; | |
const handleScroll = () => { | |
updatePosition(); | |
}; | |
onMounted(() => { | |
// Select the element using data-testid attribute | |
targetElement = document.querySelector('[data-testid="test-item"]'); | |
if (targetElement) { | |
updatePosition(); // Initial position calculation | |
window.addEventListener('scroll', handleScroll); // Listen to scroll events | |
} else { | |
console.error('Element with data-testid="test-item" not found'); | |
} | |
}); | |
onUnmounted(() => { | |
// Clean up the event listener | |
window.removeEventListener('scroll', handleScroll); | |
}); | |
</script> | |
<style> | |
.spacer { | |
height: 800px; | |
background-color: #f0f0f0; | |
} | |
.target-item { | |
background-color: lightblue; | |
padding: 20px; | |
text-align: center; | |
margin: 20px 0; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment