Well that code is too long, so I'll just give you an idea:
Make a function that detects collision You can easily program it, or check for some online tutorials.
Make a function that keeps track of you elements position.
Make a function that detects the edges of an element.
Finally, find a creative way to connect all of the three functions mentioned above :)
Not sure if this is the best solution, but that's how I would do it..