Site icon Hip-Hop Website Design and Development

How to make the header "sticky" using Javascript when page is scrolled

I am currently using the Astra free theme, which comes with a setting for a transparent header. I want the header to lose transparency and "stick" to the top when the page is scrolled down. Instead of using plugins I want to do this with CSS/JS. My current idea is to detect when the page is scrolled, and depending on the current position, apply/remove the CSS class responsible for "stickiness".  

This is what I have so far code wise, but it does not seem to work. Any tips would be greatly appreciated!  

<style>.stickyheader{
    position: fixed;
top: 0;
width: 100%; 
}
</style>
<script>
window.onscroll = function() {
var mainHeader = document.getElementById("masthead");
if(document.documentElement.scrollTop ==0)
{//header should be transparent, scroll position is at top
    mainHeader.classList.remove("stickyheader");
}
else
{//webpage was scrolled down, make header sticky
    mainHeader.classList.add("stickyheader");
}
};    
</script>