Refactor js

**Resolves issues #777 and #780.**

---

Rewriting our js to be more readable and less hacky.



This applies anywhere else we have this pattern.