partiz
partiz

Reputation: 1216

jQuery and detect position of scroll in realtime

hi there how can I change this algorithm to correct jquery or javascript version?

    $(window).scroll(function () {
    var y = $(window).scrollTop();
    if (y > 50px)        {
        alert("top visible");$('header').addclass('show');
    } else {
        alert("top invisible");$('header').addclass('hide');
    }
});

Upvotes: 0

Views: 833

Answers (2)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

scrollTop() returns an integer, representing the number of pixels.

50px is not an integer, and it will throw an error.

Instead, change:

y > 50px

to this:

y > 50

Also note that addClass() has a capital C.


If you're simply showing and hiding the header, you can use show() and hide(). You can then test the visibility to determine if the alert should fire or not:

$(window).scroll(function () {
  var y = $(window).scrollTop();
  if (y > 50 && !$('header').is(':visible')) {
    alert("top visible");
    $('header').show();
  } 
  else if(y <= 50 && $('header').is(':visible')) {
    alert("top invisible");
    $('header').hide();
  }
});

Fiddle

Upvotes: 2

Paul Browne
Paul Browne

Reputation: 752

Use console.log instead of alerts to see whats going on behind the scenes

$(window).scroll(function () {
    var y = $(window).scrollTop();
    if (y > 50)        {
        console.log("show");
        $('header').addClass('show').removeClass("hide");
    } else {
        console.log("hide");
        $('header').addClass('hide').removeClass("show");
    }
});

http://jsbin.com/hobehi/edit?js,console,output

Upvotes: 0

Related Questions