Caro Caro - 2 months ago 24x
jQuery Question

jsfiddle how do I get the scrollTop value inside a fiddle

Here is the jsfiddle

I want the classes to change when the

reaches the values specified in the if statement...

I don't know what stupid mistake I have made that I can't get it to work


There are a few things wrong with your code:

  • I don't think jQuery has an onscroll function
  • You have a missing closing bracket on your second if $('#main' <- here
  • Staying with that if, you have missed the brackets off the scrollTop function
  • You are checking the scrollTop value of main - it will always be 0 as it never scrolls, you are scrolling the window

Try the following (changes in comments);

$(window).on('scroll', function() { // change to scroll rather than onscroll
  var scrollTop = $(this).scrollTop(); // get scroll top of the thing that is scrolling and cache for better performance
  if (scrollTop > 100) {
  } else if (scrollTop > 500) {
    $("#container").removeClass("red").addClass("blue"); // chain actions
  } else {
    $("#container").removeClass("red blue"); // you can pass two classes into this

If you use this in your fiddle and inspect the container, you will see the class get added (you won't see it change colour as it goes off screen before the class changes)