0

I need some help linking my JS file to my html file after I linked jQuery from Google CDN. I could do and put the code inside, but it makes my code look untidy.

This is what I'm doing:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</script>
<script src="images/script.js"></script>
<script src="script.js"></script>

After that, my code does not work. However, when I put it into script tags, it does. I'm linking to script.js correctly, but the code doesn't activate when I try clicking on something. What can I do to fix this?

The code I created was:

$('div').on('click', function () {
    $(this).toggleClass('show-description');
}); 

Thanks!

6
  • 2
    Can you please add the code you created as well. Also, check the console for errors. Commented Apr 27, 2015 at 17:05
  • However, when I put it into script tags, it does. If it's a script it needs to be put in script tags. Commented Apr 27, 2015 at 17:07
  • So I can't link it outside of the html document? Commented Apr 27, 2015 at 17:08
  • @chRyNaN, I believe OP is meaning doing <script>code</script> instead of <script src="..."></script> Commented Apr 27, 2015 at 17:08
  • Do view source of your page, click on the script.js and see if it takes you to the desired file. Commented Apr 27, 2015 at 17:09

2 Answers 2

1

Try putting your code within document ready function from jQuery. The issue is your DOM is not ready at the time you defined the onclick handler.

jquery document ready function

  $( document ).ready(function() {

    $('div').on('click', function() {
      $(this).toggleClass('show-description');
    }); 
  });
Sign up to request clarification or add additional context in comments.

1 Comment

@Edwin Mark this answer as correct if it solved your problem. Also try not to put your script tags inside the head. Instead put them just before closing </body> tag. Thanks :)
0

Check your file pathway for your script.js file in regards to your html file.

1 Comment

Could you please add more details to the solution you provided?

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.