Hello! There is a script that sticks a block, and specifically a sidebar, on the site page. The sidebar block in the file was wrapped in the .sticky-block and .sticky-block .inner classes for the script to work.

<script> $(window).scroll(function() { var sb_m = 60; /* отступ сверху и снизу */ var mb = 300; /* высота подвала с запасом */ var st = $(window).scrollTop(); var sb = $(".sticky-block"); var sbi = $(".sticky-block .inner"); var sb_ot = sb.offset().top; var sbi_ot = sbi.offset().top; var sb_h = sb.height(); if(sb_h + $(document).scrollTop() + sb_m + mb < $(document).height()) { if(st > sb_ot) { var h = Math.round(st - sb_ot) + sb_m; sb.css({"paddingTop" : h}); } else { sb.css({"paddingTop" : 0}); } } }); </script> 

Where there is no sidebar, it displays an error that there is no element

 Uncaught TypeError: Cannot read property 'top' of undefined 

How can this error be avoided? On all pages, sidebars do not put an option, it is not very much in the scripts. Wordpress website. thank

  • Wrap the function in a condition of type if ($ (". Sidebar"). Length) {function () {}} - Alexander

1 answer 1

Add 1 line if (sb.length === 0) return;

 <script> $(window).scroll(function() { var sb_m = 60; /* отступ сверху и снизу */ var mb = 300; /* высота подвала с запасом */ var st = $(window).scrollTop(); var sb = $(".sticky-block"); if (sb.length === 0) return; var sbi = $(".sticky-block .inner"); var sb_ot = sb.offset().top; var sbi_ot = sbi.offset().top; var sb_h = sb.height(); if(sb_h + $(document).scrollTop() + sb_m + mb < $(document).height()) { if(st > sb_ot) { var h = Math.round(st - sb_ot) + sb_m; sb.css({"paddingTop" : h}); } else { sb.css({"paddingTop" : 0}); } } }); </script> 
  • Very cool! Thank you very much! - Leo
  • If the answer is useful, it is worth noting as accepted by a check mark below. This will help navigate users who are looking for the answer to a similar question. - KAGG Design