within-view
within-view uses preact/react hook to detect scroll event changes and checking if the wanted element(s) is within view and appending a class to the element if desired.
Install
Usage
isWithinView ( { y , key , id , ref , class , skipEl , offset , repeatedly , addParentOffset , add , skipCb , cb } )
useScrollPosition ( effect , dependencies , wait )
Preact / React integration
import { isWithinView , useScrollPosition } from ' within-view/preact '
import { isWithinView , useScrollPosition } from ' within-view/react '
Example
Add inView class to element
import { isWithinView , useScrollPosition } from ' within-view/**(preact/react)** '
useScrollPosition ( ( { position } ) => {
const p = {
y : position . y ,
add : ' inView '
}
isWithinView ( { ... p , id : ` helloWorld ` } )
isWithinView ( { ... p , class : ` helloWorld ` } )
isWithinView ( { ... p , query : ` .helloWorld ` } )
isWithinView ( { ... p , ref : helloWorlRef } )
isWithinView ( { ... p , query : ` .helloWorld .inner #first ` } )
isWithinView ( { ... p , repeatedly : false } )
isWithinView ( { ... p , addParentOffset : true } )
isWithinView ( { ... p , skipEl : true } )
} , [ ] , 50 )
Call another function when within view and skip the element on done
import { isWithinView , useScrollPosition } from ' within-view/**(preact/react)** '
import { useState } from ' preact/hooks '
const [ seenAlert , setSeenAlert ] = useState ( false )
useScrollPosition ( ( { position } ) => {
const p = { y : position . y , add : ' inView ' }
isWithinView ( {
y : position . y ,
skipEl : seenAlert ,
class : ` scheduleDemo ` ,
offset : 120 ,
skipCb : seenAlert ,
cb : ( ) => {
setSeenAlert ( true )
alert ( ' Dont miss out! ' )
}
} )
} , [ inView ] , 50 )
Bonus: Scroll direction
import { useScrollPosition } from ' within-view/**(preact/react)** '
import { useState } from ' preact/hooks '
const [ seenAlert , setSeenAlert ] = useState ( false )
useScrollPosition ( ( { direction } ) => {
console . log ( ` I'am scrolling ${ direction } ` )
} , [ ] )
Bonus: Hide header on scroll
import { useScrollPosition } from ' within-view/**(preact/react)** '
import { useState } from ' preact/hooks '
const [ hideHeader , setHideHeader ] = useState ( false )
useScrollPosition ( ( { position } ) => {
const headerShouldBeHidden = position . y > 250
if ( headerShouldBeHidden !== hideHeader ) {
setHideHeader ( headerShouldBeHidden )
}
} , [ hideHeader ] , null , 100 )
return (
< header class = { hideHeader && ' hide ' } >
< a href = ' / ' > Within View < / a >
< / header >
)