refactor js into re-usable function