Ash
Ash

Reputation: 822

Javascript addEventListener working in Firefox and IE but not Chrome?

This works in Firefox and Internet Explorer, but does not work in Chrome, I have tested on multiple computers running Chrome.

Is there something I have missed that causes this not to work in Chrome?

<script>
document.addEventListener('DOMContentLoaded', function() { 
    var dealBar = function() {
        var scroll = document.documentElement.scrollTop;
        var sidebarDeals = document.querySelector('#sidebar__deals');
        var sidebarAdverts = document.querySelector('#sidebar__adverts');
        var adBottom = sidebarAdverts.offsetTop + sidebarAdverts.clientHeight;

        if (scroll > adBottom) {
            sidebarDeals.className = "sidebar__deals--fixed";
        } else {
            sidebarDeals.className = "sidebar__deals--relative";
        }       
    }

    window.addEventListener('scroll', function(e){
        dealBar();
    });
    dealBar();
});
</script>

I get no errors in the Console.

Upvotes: 0

Views: 1197

Answers (2)

Ash
Ash

Reputation: 822

Wasn't a problem with the event listener.

Changing

var scroll = document.documentElement.scrollTop;

to

var scroll = (document.documentElement.scrollTop || document.body.scrollTop);

This done the trick, seems Chrome bases its scroll position off of <body> and Firefox bases it off of <html>.

Chrome was returning 0 for scroll causing the function not to trigger the class change.

Upvotes: 1

G&#244;T&#244;
G&#244;T&#244;

Reputation: 8053

Your code is correclty triggered when I remove the first part related to the DOMContentLoaded event: demo.

I think your problem lies here, Chrome probably executes your code after the DOM is loaded, thus your code is never executed.

Try to remove this part:

<script>
//document.addEventListener('DOMContentLoaded', function() { 
    var dealBar = function() {
        var scroll = document.documentElement.scrollTop;
        var sidebarDeals = document.querySelector('#sidebar__deals');
        var sidebarAdverts = document.querySelector('#sidebar__adverts');
        var adBottom = sidebarAdverts.offsetTop + sidebarAdverts.clientHeight;

        if (scroll > adBottom) {
            sidebarDeals.className = "sidebar__deals--fixed";
        } else {
            sidebarDeals.className = "sidebar__deals--relative";
        }       
    }

    window.addEventListener('scroll', function(e){
        dealBar();
    });
    //dealBar();
//});
</script>

Also, regarding the scroll position, you may want to check this post: JavaScript get window X/Y position for scroll

Upvotes: 1

Related Questions