Refactor js

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

I used when more for the purpose of readability in these cases.