Dynamic Drag Alignment Rulers {elegance sometimes happens}

In most cases when you work on a product, requests from ‘those who shall be obeyed’ and I don’t mean your mother, are fairly simple.  You are given a functional idea or a behavior to be implemented within a product and you say to yourself ‘yep, no problem’. In other words, not often is there a challenge. Then there are those rare cases where you come across a task where you need to think outside of the box and we all crave those tasks. Such is a task that I recently faced on a product I work on.  In essence think of the product as an online version of Microsoft PowerPoint, it’s not, but it’s the closest I can think of in the context of the post. The request was to display rulers top, bottom, center, middle, left and right on the selected object. As the object was dragged around the screen when any of these rulers came into alignment on the X or Y of any other object they were to be displayed.  A very similar UI behavior that you would see in PhotoShop, for example.  To make it even more difficult the rulers had to gradually get stronger as it got close to any alignment on any other element on the page on its 3 horizontal or 3 vertical axis!

So imagine the below scenario:

So in the above image there are three shapes.  The blue square has been selected and when any of the 3 horizontal rulers comes into contact with the top, middle or bottom of the other shapes they would need to appear.  Same goes for the vertical if the user where to drag the blue square to the right. So this means that for each element/shape on the page there are 3 vertical and 3 horizontal points to compare to the current points on the actively dragged element, in this case the blue box. Now consider you could have any number of shapes you need to align to! This leads one to the conclusion that any sort of heavy on the fly calculation while dragging will simply destroy performance.  So the question then becomes how can we do this with ZERO calculations/conditions while the selected element is being dragged.  The answer is YES we can and here is how. Just a quick note regarding some of the code, in order to preserve the privacy of the application I am not using the general namespace we use for our toolkit that provides DOM manipulation. However you can easily see how to do this in jQuery, ExtJS etc.  The point is the solution not so much the implementation. Continue reading