If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:
In your CSS use (for example)
div.centered{
width: 100px;
height: 50px;
position:fixed;
top: calc(50% - 25px); // half of width
left: calc(50% - 50px); // half of height
}
No JS required.