It seems that there may be a scope issue within my helper function. I have successfully implemented the same logic in my component and it works flawlessly.
I have already utilized a composable function to incorporate ref() with the variable that needs to be returned.
=> This is the functioning code within my component
// component.vue
setup() {
const subnavDiv = ref(false) // this variable gets updated by the code below
onMounted(() => {
const routEl = document.querySelector('.main')
const fixedNav = document.querySelector('.main-nav')
const el = document.querySelector('.search')
let prevYPosition = 0
let directionVar = 'up'
const options = {
root: routEl,
rootMargin: `${fixedNav.offsetHeight * -1}px`,
threshold: 0.7
}
const setScrollDirection = () => {
if (routEl.scrollTop > prevYPosition) {
directionVar = 'down'
} else {
directionVar = 'up'
}
prevYPosition = routEl.scrollTop
}
const onIntersection = ([e]) => {
setScrollDirection()
if ((directionVar === 'down' && e.boundingClientRect.top > 0) || !e.isIntersecting) {
console.log('down')
subnavDiv.value = true
} else {
subnavDiv.value = false
}
if (
e.isIntersecting &&
(e.boundingClientRect.top < fixedNav.offsetHeight ||
e.boundingClientRect.top > fixedNav.offsetHeight)
) {
subnavDiv.value = false
}
}
const observer = new IntersectionObserver(onIntersection, options)
observer.observe(el)
})
return {
subnavDiv
}
}
}
=> After moving the same code out of the component
// component.vue
setup() {
const subnavDiv = ref(false)
onMounted(() => {
const rootEl = document.querySelector('.main')
const fixedNav = document.querySelector('.main-nav')
const el = document.querySelector('.search')
subnavDiv.value = onIntersect(rootEl, 0.7, fixedNav, el) // Function call for the helper function: The purpose of this line is to update the value of subnavDiv
})
})
/////////////////////// $$$$$$$$$$$$$$$$$$ ///////////////
onIntersect.js // The helper function
const onIntersect = (rootElement, thresholdValue, elementToChange, elementToWatch) => {
let prevYPosition = 0
let directionVar = 'up'
const options = {
root: rootElement,
rootMargin: `${elementToChange.offsetHeight * -1}px`,
threshold: thresholdValue
}
let bool = false // The variable I am attempting to return from this function
const setScrollDirection = () => {
if (rootElement.scrollTop > prevYPosition) {
directionVar = 'down'
} else {
directionVar = 'up'
}
prevYPosition = rootElement.scrollTop
}
const onIntersection = ([e]) => {
setScrollDirection()
if ((directionVar === 'down' && e.boundingClientRect.top > 0) || !e.isIntersecting) {
console.log('down')
bool = true
} else {
bool = false
}
if (
e.isIntersecting &&
(e.boundingClientRect.top < elementToChange.offsetHeight ||
e.boundingClientRect.top > elementToChange.offsetHeight)
) {
bool = false
}
}
const observer = new IntersectionObserver(onIntersection, options)
observer.observe(elementToWatch)
return bool // The return statement (not returning anything)
}
export default onIntersect