Tuesday, April 22, 2008

Make space for moving divs between other divs

I am glad today because I really found a better way of doing things than what I had found. Isn't the feeling of achievement which gives the best exhilaration?
Problem - You have a list of divs. You have to make these divs movable and when it is moving, it should become transparent and when it is put on some other div in the list, the latter should move to the former's place to make space for it to land.
Solution on net -
  1. Make a list of divs.
  2. Make them transparent as discussed in the last post.
  3. Keep the left, top, width and height of divs as attributes.
  4. As the mouse moves, check if the mouse has entered some other div's dimensions and if so swap it with the position of the div being moved
  5. If the target div is not the last div, then get its next div and move the source div before its next sibling using insert before
  6. If the target div is the last div use appendchild

My solution -

3. Why the dimensions of the div is to be kept is very important. Since the moving div was always found to be above the target div, no mouse events reached the target div. Therefore this round about solution was used. I found a way to keep the source div beneath the target div. In the process I learnt about the z-index. z-index only works when its scope is the same. In other words, z-index only works correctly when it is used to order sister elements. Therefore the z-index of the parentNode can only be compared to the those of its sister elements and not its children. Similarly the z-index of the children cannot be compared with its parents. And yeah, the z-index only when the position attribute is explicitly set to absolute / relative

Anyway, so finally, by adjusting the z-index, I positioned the divs correctly and now the source div was always below the target div and now all the mouse events reached it. Now on mouseover, I can swap the positions. Saved a lot of CPU :)

5. Not much improvement here, just a little more elegant method. If the source div is before the target div, then the target div has to be inserted before the source div. This is done by insertBefore method. if the source div is after target div, then the source div is to be inserted before the target div

All this can be seen in action at fewbs.com. (not immediately, the release is not final. Check in a weeks time)

No comments: