-2

I found these sample code from here

The code is like this:

<script>
    $("#modal2Button").click(function() {
      $("#modal1").fadeOut();
      setTimeout(function() {
        $("#modal2").fadeIn();
      }, 400)
    });


    $("#close-button").click(function() {
      setTimeout(function() {
        $("#modal1").fadeIn();
        $("#modal2").fadeOut();
      }, 1000)

    });
</script>

When I paste the jQuery as a separate file and link it inside the <head>

<head>
<script src="sample_code.js"></script>
</head>

and for some reason that does not work?

Any help will be much appreciate!

DAVE
  • 111
  • 11
  • Is the file path correct? If your JavaScript is beside your HTML file, then you might need to do `` – Robert Cooper May 27 '19 at 03:46
  • try to inspect element in web page, in browser press F12 to open devtools and try to find your javascript import, check is it accesable or not. if not accessable then add `./` before the filename.js Like `src="./sample_code.js"` – Dupinder Singh May 27 '19 at 03:51
  • 1
    @RobertCooper thanks for your help, seems the path causing the problem! – DAVE May 27 '19 at 03:56
  • @DupinderSingh Thanks I tried press F12, It seems a better way to check if the file imported! – DAVE May 27 '19 at 04:39

2 Answers2

1

This is simply a matter of making sure you're using the correct path to your JavaScript file:

<head>
  <script src="./sample_code.js"></script>
</head>

Notice the ./ before the file name, which indicates the file is on the same level as your HTML file.

Robert Cooper
  • 2,160
  • 1
  • 9
  • 22
0

Yes, Definitely it will not work because the DOM Elements are yet not loaded, and you are accessing them, so their will be an error undefined id modal2Button same for the next one.

If you run your js file when all DOM Elements are loaded their will be no problem..

You can do that via following:

vaku
  • 697
  • 8
  • 17
  • you just solved my next question! I have to move the tag to the bottom of the html, its a DOM problem! thanks a lot. – DAVE May 27 '19 at 04:07
  • your answer definitely explain a very good point to new guy like me, please help [here](https://stackoverflow.com/questions/55543180/jquery-does-not-work-in-seperate-file-but-works-when-i-put-it-in-the-body-of-my/56319113#56319113) – DAVE May 27 '19 at 04:58