Trevor Judice
Trevor Judice

Reputation: 137

JQuery ScrollTop not working with Overflow

When building my mobile website, I had to add these properties to my body to eliminate excess whitespace:

html,body
{
    width: 100%;
    margin: 0px;
    padding: 0px;
    overflow-y: scroll;
    overflow-x: hidden; 
    -webkit-overflow-scrolling: touch;
}

However, my jQuery scrollTop functions, regarding parallax and the navbar, do not work now. These functions do not work on mobile.

$n = ".navbar";
$(window).scroll(function(){
    if($(window).scrollTop() > 300){
        $($n).css("background-color", "rgba(255,255,255,.2)");
    } else {
        $($n).css("background-color", "transparent");
    }
});

I have tried removing the overflow from the body, and keeping it solely on HTML, and vice versa, which does fix my issue, however the whitespace returns. I have looked online, however I cannot seem to find anything regarding this issue.

If you want to view the website, the URL is http://studysesh.us. Keep in mind, it is just beginning, currently the homepage is the only page. Thank you.

Upvotes: 1

Views: 2449

Answers (3)

Colin
Colin

Reputation: 1836

I had this same issue where scrollTop() was not working. Turns out it was because I had some inline styles at the top of the page. It seems scrollTop() expects a certain HTML structure so having the <style> tag as the first element on the page breaks it. This is what it looked like before the fix:

<style>
    .my-class {
        ...
    }
</style>
<!doctype html>
<html lang="en">
    <head>
        ...
    </head>
</html>

I moved the inline stylse into the <head> tag which resolved the issue. Here's how it looks after the fix:

<!doctype html>
<html lang="en">
    <head>
        <style>
            .my-class {
                ...
            }
        </style>
    </head>
</html>

Upvotes: 0

Ahmad Baktash Hayeri
Ahmad Baktash Hayeri

Reputation: 5880

Figured it out by removing the height property on the body, which literally is equivalent to setting the height to auto.

body {
   height: auto;
   max-width: 100%;
}

When you set a value to the height of the body explicitly, scrolling on any area over it would actually trigger scroll event inside the body itself, and not the window. In my opinion, this was the source of the problem with the scroll event not being fired.

Meanwhile, overflow-y: scroll; is redundant and needless in your case, as it forces an ugly scroll-bar on the body when the width of the viewport is reduced significantly.

Upvotes: 2

Jikar
Jikar

Reputation: 48

I think it might be caused by the

overflow-y: scroll;
overflow-x: hidden;

Try to change them by

overflow: auto;

Upvotes: 0

Related Questions