updated code to use elem.getBoundingClientRect() as suggested by @7cc