Refactor javascript functionality