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
- js
- homePage.html
I’ve tried to put the script tag on the bottom, but still no answer from the js file
2
Answers
The path for
scripts.js
onsecondPage.html
should be../js/scripts.js
, since both are in the same folder. (data
)Note: but as someone stated in the comments, you should favor referencing via its absolute path. (
/data/js/scripts.js
)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 thedata
folder, then thejs
folder, then thescript.js
file.With the second page
secondPage.html
, it also goes up one level, but this time that level above is thepages
folder. It tries to search fordata
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.