Refactored code to make more DRY. Added keypress function