Home > Enterprise >  window.scrollTop is undfined
window.scrollTop is undfined

Time:12-02

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.

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?

CodePudding user response:

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>

CodePudding user response:

<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>

YESSINE's code is correct. but can make it simple

<script>
jQuery(window).on('scroll', function() {
        var window = $(window);
        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>
  • Related