Reza Abbasi
Reza Abbasi

Reputation: 1591

.offset function inside .scroll function not works in jQuery

I want to detect the top of '#select' element when scrolling. I have following codes:

$(document).ready(function(){
  $(window).scroll(function(){
    console.log($('#select').offset().top);
  });
});
<div id="select"></div>

But the thing it prints is not fixed during scrolling and I think it is the value of $(window).scrollTop(). when I put 'console.log ...' outside of '$(window)....' function everything works fine. What is the problem?

I found now the problem is from selector. In some cases when I changed the id it works fine, but for the 'select' id it not works and all the time it prints $(window).scrollTop() . Any one can help in this case? (Perhaps there is some problem with the css of '#select' element)

Upvotes: 0

Views: 389

Answers (1)

Nicola Pulvirenti
Nicola Pulvirenti

Reputation: 29

You are probably missing some brackets...

Try this...

$(document).ready(function(){
  $(window).scroll(function(){
    console.log($('#select').offset().top);
  });
});

Upvotes: 1

Related Questions