If you want me (or someone ) to check your code its a good idea to allow us to copy and paste it. What you posted was a screenshot of the source and I won't have time to type it out and debug it. You can use the pre-formatted text formatting option when copying-and-pasting code into the html area. (Then it looks a bit like code and doesn't go all massive)
I am not sure what that error is but generally speaking, you should put the javascript into the custom js area of the template. Then it will load it in an AMD module and it works a lot nicer like that. The attached template bundle will do something like what you are doing. I hope it gives you some ideas.
(You can just drag the template bundle over the green bundle box on a template settings page and it will autofill the template fields.)