I think trying to make this function generic may be better.  If I vaguely remember there was some jquery plugin that did something similar to this. You could maybe try to find it and use it for inspiration.