• Absolute positioning in Prototype JS relative to an element

    Posted by markzero on Thursday, November 18th, 2010

    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" 
    +'px; />','top');

    cumulativeOffset returns an array of two elements which determines x and y positions of the element. Link5[0] sets x coordinate 20px to the right of the link (if we wanted to the left then put “-20”), while link5[1] sets y, the same as link5’s top position.

    Pretty cool huh?

    Write comments and question down there…

    Posted in: Featured, Javascript, Prototype JS.

    Share this story:

    3 responses to “Absolute positioning in Prototype JS relative to an element”

    1. CSS Forum says:

      Hey! Can I add this post to my forum? It’s very great post, I would like to share it with others.

      Report this comment

    2. Mohsen says:

      It helped me. Thank you.

      Report this comment

    Leave a Reply