skip to Main Content

This is the call on the HTML:

<script type="text/javascript" src='../js/scripts.js'></script>

And this is the way I’m using to verify it works:

document.addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
        window.alert('Hello world!');
    }
});

On the Home page it works effortlessly, but in that next page it does not work, feels like it’s not triggering again to refresh the document that the js is on.

The file structure for this is:

  • data
    • js
      • scripts.js
    • pages
      • secondPage.html
  • homePage.html

I’ve tried to put the script tag on the bottom, but still no answer from the js file

2

Answers


  1. The path for scripts.js on secondPage.html should be ../js/scripts.js, since both are in the same folder. (data)

    <script type="text/javascript" src='../js/scripts.js'></script>
    

    Note: but as someone stated in the comments, you should favor referencing via its absolute path. (/data/js/scripts.js)

    Login or Signup to reply.
  2. With the home page homePage.html at the "bottom", when it looks for the file with instructions ../data/js/scripts.js, it goes up one level (the folder with everything here inside it), then looks for the data folder, then the js folder, then the script.js file.

    With the second page secondPage.html, it also goes up one level, but this time that level above is the pages folder. It tries to search for data but can’t find it.

    If you’d like to keep the file structure you already have laid out in the question, modify your script element, in that second page, to be <script type="text/javascript" src='../../../data/js/scripts.js'></script> as this will go to the root folder before looking for the data folder.

    Additionally, make sure that your <script></script> element is present in that second page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search