refactor JS code a bit