1

When I move my jQuery code residing inline from the template to an included .js file all explicit functions still work but all jQuery event-handlers stop working, they simply do nothing anymore:

still works:

function doit() {}

does NOT work anymore:

$("#my_id").click(function () {
});
2
  • 3
    Common mistake is including the JS-file BEFORE you've included the jQuery library. Commented Jan 21, 2011 at 12:03
  • for completeness: I am using the play-framework, which makes use of groovy-templates. Commented Jan 21, 2011 at 15:06

3 Answers 3

2

Let me add a little to my comment:

This will work because jquery is loaded first, then your js:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="myJavascript.js"></script>

This will not work as jQuery is not yet loaded when the custom javascript is read:

<script type="text/javascript" src="myJavascript.js"></script>
<script type="text/javascript" src="jquery.js"></script>

Not sure this is your problem, but it is a common mistake alot of people make so might be the solution. Let me know if it solved your problem or not;)

Sign up to request clarification or add additional context in comments.

1 Comment

unfortunately this is not the problem. I have a main.html in which I first include jquery.js, after that I include my.js with the extracted jquery-code.
2

To answer my own question, I had to include the .js file not in the main-groovy-template but in the template extending the main-template, then it worked.

1 Comment

It make sense if your main-template includes jquery.js at the end. Why? Because the HTML code that extends your template may do it also at the end, but its end occurs before that the end of the main template. So "at the end" your JS file is somewhere in the middle of the final HTML and the JQUERY.JS is exactly at the end.
1

Have you done it within "document.ready"?

e.g.

$(function() { //shorthand for document.ready


  $("#my_id").click(function () {

    //do something

  });


});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.