Refactored some of the JS code after chat with Alex