Absolute positioning in Prototype JS relative to an element
When you want to display an element anywhere on the page, regardless of css structure, by clicking a link or any html element, you need to display it absolute positioned. This short tutorial explains how to do it, with Prototype API.
Let’s assume we have a list of links and want to display an image 20px right to and in same line as the link. Prototype holds really cool class named Element. With it you can manipulate html structure anyway you like. This singletone class contains this method cumulativeOffset which gives you the offset of html element, no matter to page’s height and width (even including scroll bars).
So this image will have css position set to absolute, with body tag as it’s parent, so you can set it anywhere on the page.
With insert method applied to the body element we can put it on the page:
document.body.insert('<img src="img/image.png" />');
This is basic way of adding an element, but I’m gonna extend it by inserting css to this image. With this approach we have all the code in one line.
Let’s assume link element has ID attribute “link5”. Here is what you need to do to make it positioned as mantioned above:
document.body.insert('<img src="img/image.png" style="position:absolute; left:'+ (Element.cumulativeOffset($('link5'))+20)+'px; top:'+ Element.cumulativeOffset($('link5')) +'px; />','top');
cumulativeOffset returns an array of two elements which determines x and y positions of the element. Link5 sets x coordinate 20px to the right of the link (if we wanted to the left then put “-20”), while link5 sets y, the same as link5’s top position.
Pretty cool huh?
Write comments and question down there…
Share this story:
3 responses to “Absolute positioning in Prototype JS relative to an element”
Leave a Reply