Where do I put code for custom header?

I found a few tutorials that helped me achieve the effect I desired for the header to change into a compacted version on scroll. In all of the tutorials its showing the code in the page code so of course it’s only working on the Home page I initially wrote it in. I tried putting in the global code section instead but it’s not working.

$w ( '#headerTransitionPoint' ). onViewportLeave (()=> { 
    console . log ( 'viewport leave' ) 
    $w ( '#header2' ). show (); 
    $w ( '#defaultHeader' ). hide (); 
}) 
$w ( '#headerTransitionPoint' ). onViewportEnter (()=> { 
    console . log ( 'enter' ) 
    $w ( '#defaultHeader' ). show (); 
    $w ( '#header2' ). hide (); 
})

If all these elements that appear in this code snippet are global, it should work on masterPage.js