Search code examples
javascripthtmlcssmouseeventonscroll

Onscroll event not working


This time I have a problem with an animation. I would like my background's header/menu to become White when users scroll down.

The header/menu is fixed and I use the z-index property to maintain it above the rest of the page.

I have made a html test page with some JS and CSS code:

You can see the test online here: http://www.lacouleurdurendezvous.fr/test

Sorry but I tried to put the code here but the editor is a bit capricious


Solution

  • You are not using the correct code for getting the scroll position. To reference an answer for a very similar question: JavaScript get window X/Y position for scroll

    var doc = document.documentElement;
    var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
    

    This would result in an onscroll event handler like so:

    window.onscroll=function() {
        var doc = document.documentElement;
        var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
        document.getElementById('text').className=top>50 ? 'scroll' : '';
    }