Skip to content Skip to sidebar Skip to footer

Javascript Working In Fiddle But Not In Own Page (even If Script Is At The Bottom)

I'm trying to replicate this jsfiddle, which sticks the bar to the top when scrolling down; but there is something wrong which I am not able to identify. To go to the most basic ap

Solution 1:

i found that the var name top is ambiguous with window.top which is the most top frame. so just rename it with something else like as top1 solve the problem!

var top1 = document.getElementById('a8').offsetTop;

Solution 2:

Changing you script to this should do the trick.

<script>var myTop = document.getElementById('a8').offsetTop;
    window.onscroll = function() {
        var y = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
        if (y >= myTop) {
            a8.className = 'stick';
        }
        else {
            a8.className = '';
        }
    };
</script>

My initial answer was wrong, has nothing to do with the loading but it has to do with the top property of the window.

Solution 3:

It was issue with top variable but in other case when you need something to execute after page load is complete then you may wrap your script in function

document.addEventListener('DOMContentLoaded', function() {
   // your code here
}, false);

This will also work.

document.addEventListener('DOMContentLoaded', function() {
        var top = document.getElementById('a8').offsetTop;

    window.onscroll = function() {
        var y = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
        if (y >= top) {
            a8.className = 'stick';
        }
        else {
            a8.className = '';
        }
    };
    }, false);

Post a Comment for "Javascript Working In Fiddle But Not In Own Page (even If Script Is At The Bottom)"