Assuming you prefer to maintain your current implementation where span
elements are hidden until hovered over.
To determine each element's vertical position, you can use
elem.getBoundingClientRect().top
This will give you the distance from the top of the page.
You can find out the height of the window by using window.innerHeight
.
It's a simple task to check if an element's top position is greater than half of the window's height
elem.getBoundingClientRect().top > window.innerHeight/2
If this condition is met, you could apply a class to the element to have it appear above the link title. However, there are multiple ways to achieve the same result.
Let's say you want to add a class to the spans so they appear above the title, you can either position them relatively and set a negative top
css value, or you can utilize CSS3 transforms like this:
.above {
transform: translate(0, -100%);
}
In this way, you won't need to worry about the span's height since CSS transforms use the target element's dimensions, not the parent container's.
Another important consideration is optimizing script load. You may want to check the position of the span
element in the `onhover` event listener instead of checking all spans when the DOM is ready. Checking all spans at once can pause rendering and make the page seem unresponsive until the script loads.