Reputation: 57
I am having problems running a simple jQuery script in an external js file.
$("#main-nav").click(function(){
alert("hello");
});`
I declared the external js file here in my html after the jQuery file.
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="externalfile.js"></script>`
Nothing happens when I load the page and I get no errors in the console.
Upvotes: 0
Views: 80
Reputation: 4091
Taking a guess since there isn't enough information here, but I'm relatively certain you've placed these <script>
tags in your <head>
, where they will be executed before the DOM is ready. Since the DOM isn't ready, you can't bind a click event to it. Wrap your code in $(document).ready()
:
$(documment).ready(function () {
$("#main-nav").click(function(){
alert("hello");
});
});
Now your code to bind the click handler will run after the DOM is ready and able to have events bound to it.
Upvotes: 3