Refactored viewport JS code