Your issue is that you're trying to replicate CSS functionality with other CSS functionality. Instead of having #rightSideBar
positioned relatively and setting the top value to a value based on the distance from the top of the page to show in the viewport, your should be doing this:
#rightSideBar { position:fixed; right: 20px; top: /* set this value with Javascript */ }
This feature of CSS fixes the position of an element to the viewport, where you specify, so all you need to do is set how far from the top of the user's browser's viweport your want your element to appear. This will not be a value from the top of the page, but instead the number of pixels from the top of their window, regardless of its size, position or content.