The code you've linked to looks decent and as far as I know it should work. If I were you however I would start by diving into jQuery source to look for how they are doing it, since jQuery is under constant development, unlike (assuming) example from developer.Mozilla.
Replace jQuery with any other library you're feeling comfortable with looking into.