Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

window.scrollTop is undfined

why would window.scrollTop be undefined?

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

The Element.scrollTop property gets or sets the number of pixels that
an element’s content is scrolled vertically.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

An element’s scrollTop value is a measurement of the distance from the
element’s top to its topmost visible content. When an element’s
content does not generate a vertical scrollbar, then its scrollTop
value is 0.

jQuery(window).on('scroll', function() {
        if(window.scrollTop > 0) {
            console.log('of the top')
            console.log('scroll top value is: ' + window.scrollTop)
        } else {
            console.log('the top')
            console.log('scroll top value is: ' + window.scrollTop)
        }
    })

All I’m getting in my console log is:

scroll top value is: undefined

and I’m always getting an evaluation of in the if else:

of the top

even if I’m scrolled to the top of the page.

Why would window.scrollTop be undefined?

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop does window not count as an element?

>Solution :

You need to use the jQuery $ identifier as well as the parenthesis () for .scrollTop() in order to get the position

Here’s the executable code:

<script>
jQuery(window).on('scroll', function() {
        if($(window).scrollTop() > 0) {
            console.log('of the top')
            console.log('scroll top value is: ' + $(window).scrollTop())
        } else {
            console.log('the top')
            console.log('scroll top value is: ' + $(window).scrollTop())
        }
    })
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading