-4

How can I modify the script below so that it doesn't throw an error when the ".fixit" element is not present in the DOM?

function fixedHeaders() {
       var el = jQuery('.fixit'),
           offset = el.offset(),
           elHeight = el.height(),
           scrollTop = jQuery(window).scrollTop()
           if (((offset.top + 400) < scrollTop - el.height())) {
               el.addClass('fixedElement');
           }

       if (scrollTop === 0) {
           el.removeClass('fixedElement');
       }
}
jQuery(function() {
   jQuery(window)
       .scroll(fixedHeaders)
       .trigger("scroll");
});
RegEdit
  • 2,096
  • 10
  • 37
  • 62

2 Answers2

1

Start with

if (!jQuery('.fixit').length) return;
Denys Séguret
  • 355,860
  • 83
  • 755
  • 726
0
if ($('.fixit').length) {

     var el = jQuery('.fixit'),
           offset = el.offset(),
           elHeight = el.height(),
           scrollTop = jQuery(window).scrollTop()
           if (((offset.top + 400) < scrollTop - el.height())) {
               el.addClass('fixedElement');
           }

       if (scrollTop === 0) {
           el.removeClass('fixedElement');
       }

}
mikea80
  • 129
  • 1
  • 5