Added borrowed code for smart scrolling