Sunday, March 4, 2012

jQuery relative position plugin - nextTo


The Problem :
I've already created quite a few jQuery plugins in the past, at work, and for personal use, and in many of them there are certain parts of code that always tend to repeat themselves.

One of these parts of code has to do with element positioning calculations relative to another element.
For example, when creating a plugin for a drop-down menu, or a tooltip, you can't avoid having a nasty piece of code in there, that all it does is calculate the element's position relative to the element we clicked on or hovered above.

I don't think there's any need for me to post an example of this, you probably know what I mean. This is usually the least most maintainable part of code in the plugin and the least easy to understand.

The Solution :
I finally decided to extract this ugly piece of code into a nice jQuery plugin that will hold all the dirty work calculations, and will leave you with a nice clean and understandable piece of code inside your plugin.

<scrip type="text/javascript">
    $(function() {
        $('.PutThisDiv').nextTo('.ThisOtherDiv', {position:'right', shareBorder:'top'});
    });
</script>


This plugin is hosted on google code : https://code.google.com/p/next-to/ (project name: 'next-to')
At the project page you will find more sample usages, usage explanations, the source code and a minified version.

3 comments:

  1. I didn't like two things...
    one is that all the code is in one main function, could be broken to a few small ones which would make it very pretty,
    also.. I don't think this will work for relative objects right? I mean at this point it makes the object absolute positioned to the body element
    this can cause a lot of problems in many situations..
    also you should add an option for z-index

    ReplyDelete
    Replies
    1. @Guy - If you find situations that the code doesn't work in them, then submit a patch and the plugin will improve. That's the point in open-source! :)
      I don't think there's a need for z-index, since this is only a positioning helper for other plugins. z-index is something very easy to implement yourself so anyone can do what they want with the z-index.

      Delete
  2. This comment has been removed by a blog administrator.

    ReplyDelete