0

HTML

<div id='countdown'></div>

Jquery

<script>
  var elementPosition = $('#countdown').offset();

  $(window).scroll(function(){
    if($(window).scrollTop() > elementPosition.top){
          $('#countdown').css({'position':'fixed','top':'0'});
    } else {
        $('#countdown').css('position','static');
    }    
  });
</script>

This code is working on JSFiddle, but when I tried it, it didn't work for me.

I tried looking on the console (developer's view) and it's pointing on elementPosition.top . However, top is unknown property. Can someone help me with this?

John Manak
  • 12,620
  • 27
  • 73
  • 114
Nixxhalle
  • 87
  • 3
  • 5
  • 10
  • Also see [Why does jQuery or a DOM method such as `getElementById` not find the element?](http://stackoverflow.com/q/14028959/218196) – Felix Kling Feb 25 '14 at 09:54

2 Answers2

1

The only reason I could see is the code is not in a dom ready handler

jQuery(function () {
    var elementPosition = $('#countdown').offset();

    $(window).scroll(function () {
        if ($(window).scrollTop() > elementPosition.top) {
            $('#countdown').css({
                'position': 'fixed',
                'top': '0'
            });
        } else {
            $('#countdown').css('position', 'static');
        }
    });
})
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
0

Put your code inside DOM ready handler $(function() { .... }); to make sure all of your elements inside the DOM have been loaded properly before executing your javascript code

$(function() {
    var elementPosition = $('#countdown').offset();

    $(window).scroll(function(){
        if($(window).scrollTop() > elementPosition.top){
            $('#countdown').css({'position':'fixed','top':'0'});
        } else {
            $('#countdown').css('position','static');
        }    
    });
});

Your code works in jsFiddle because jsFiddle has already done that part for you.

Felix
  • 36,929
  • 7
  • 39
  • 54