code refactored to use jQuery events