Roblem with custom code on linking table of content section for blog

I’m trying to build the table of contents sections on the sidebar to update on scroll. It’s working but I can’t get it to respond appropriately. Scrolling sometimes doesn’t work, only updates after scrolling up and down, and some secitons won’t link. It’s quite difficult. Could someone help me?