0

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.

2
  • Welcome to Stack Overflow. For us to help you better, it would be useful if you included details such as what exact error or issue you are encountering, what you have tried to fix it, and any other information to give more context surrounding your problem. Commented Aug 5, 2015 at 14:16
  • move those scripts before closing body tag </body> and try running it if you are declaring those script tags in head Commented Aug 5, 2015 at 14:21

1 Answer 1

3

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.

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

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.