Aleksi Tappura
Aleksi Tappura

Reputation: 71

Window Scroll Function Not Working

I was making a blog, and tried to use $(window).scroll(function(), but something prevents it from working.

I try to add class named scrolled to body when user scrolls down. Any idea which would prevent it working properly? Console doesn't give any error regarding to this.

JS

$(document).ready(function($) {
    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();

        if (scroll >= 100) {
            $("body").addClass("scrolled");
        } else {
            $("body").removeClass("scrolled");
        }
    });
});

LIVE PREVIEW

http://personaii-demo.tumblr.com/

Upvotes: 2

Views: 20048

Answers (4)

Kapilrc
Kapilrc

Reputation: 1548

Remove overflow:auto property added to the container. This will work.

Upvotes: 5

SeanCannon
SeanCannon

Reputation: 78006

Better JS:

$(function() {
    $(window).on('scroll', function() {  
        $('body').toggleClass('scrolled', $(this).scrollTop() >= 100);
    });
});

On your website, I see no css associated with .scrolled anywhere even if I apply it via the console.

Upvotes: 0

Milan and Friends
Milan and Friends

Reputation: 5610

Here's a working shorthand solution, fiddle

$(function() {
  $(window).scroll(function() {    
    var scroll = ($(this).scrollTop() > 100) ? $("body").addClass("scrolled") : $("body").removeClass("scrolled");
  });
});

Also if you're using jQueryUI then you can add a little animation to class changing process with switchClass() e.g.

var scroll = ($(this).scrollTop() >= 100) ? $("body").switchClass("default","scrolled", 1000) : $("body").switchClass("scrolled","default", 1000);

*Note: Also don't forget to include jQuery/jQueryUI libraries in your document.

Upvotes: 0

Ben
Ben

Reputation: 1143

Your function takes a $ argument, but you're not passing anything in so it gets overwritten, you should do it like this:

$(document).ready(function() {
    $(window).scroll(function() {    
        var scroll = $(window).scrollTop();

        if (scroll >= 100) {
            $("body").addClass("scrolled");
        } else {
            $("body").removeClass("scrolled");
        }
    });
});

Upvotes: 0

Related Questions