Search code examples
javascriptjquerystickytypeerror

Trying to Make a Div Sticky at certain position but an Uncaught TypeError broke other codes


I'm trying to make a div sticky while scrolling, and unstick at a certain height.I got the code below and edited it. It worked but an error in it affected other Jquery scripts from working. When I checked console for the error, I got this:

Uncaught TypeError: Cannot read property 'top' of undefined at HTMLDocument.

jQuery(function($) {
  $.fn.scrollBottom = function() {
    return $(document).height() - this.scrollTop() - this.height();
  };

  var $el = $('#imgsticky');
  var $window = $(window);
  var top = $el.parent().position().top;

  $window.bind("scroll resize", function() {
    var gap = $window.height() - $el.height() - 170;
    var visibleFoot = 970 - $window.scrollBottom();
    var scrollTop = $window.scrollTop()

    if (scrollTop < top + 50) {
      $el.css({
        top: (top - scrollTop) + "px",
        bottom: "auto"
      });
    } else if (visibleFoot > gap) {
      $el.css({
        top: "auto",
        bottom: visibleFoot + "px"
      });
    } else {
      $el.css({
        top: 60,
        bottom: "auto"
      });
    }
  }).scroll();
});

How do I fix this please?


Solution

  • Check if the jQuery object contains any element before you try to get its position:

    var parentEl = $el.parent();
    var top =0;
    if (parentEl.length) {
       top = parentEl.position().top;
    
    }