-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,134
  • 10
  • 37
  • 63

2 Answers2

1

Start with

if (!jQuery('.fixit').length) return;
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
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
  • 127
  • 1
  • 5