Placement and execution of javascript

Hi,
As an absolute beginner in Javascript, I’ve hit a problem.
1.I need to execute two scripts (one js, and one Ajax) script in the same page, so decided to put them both in a JS folder, and use src= syntax to access them both. However, VSCode brings up errors when I separate this script from a page. Here’s the script:

      <script defer="true">
         const elSidebar = document.getElementById("sidebar");
         const elButton = document.getElementById("Button");

         const toggleSidebar = () => {
            elSidebar.classList.toggle("hidden");
         }
         elButton.addEventListener("click", toggleSidebar);
      </script>

The errors seem priamrily to do with formatting. The other script is an Ajax live search script. Can these two live together in the same page?

If you’re accessing the js from a <script src="myjs.js"> tag, it doesnt need <script> around it. It’s already in a script block in the main page.

the src attribute basically translates as “insert whatever’s in this file, inside this tag”

<script src="myjs.js"></script>

1 Like

For example:

main.js (separate js file)

const elSidebar = document.getElementById("sidebar");
const elButton = document.getElementById("Button");
const toggleSidebar = () => {
    elSidebar.classList.toggle("hidden");
}
elButton.addEventListener("click", toggleSidebar);

index.html (html file)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/style.css">
</head>

<body>
    ... your html here
    <!-- import main.js at the bottom of the body -->
    <script src="main.js"></script>
</body>

</html>
1 Like

Now as far as positioning goes (as the title mentions it)…

Scripts are usually executed at the time and place where they exist in the document. So if your second script relies on elSidebar being defined, then the second script tag must come after the first; and they both must come after the element with ID “sidebar” in the HTML.

I’m a little foggy on what happens with deferred scripts, though… so that last bit may not be true for deferred scripts. (I generally dont bother deferring my scripts… and i’m not sure deferring a 4 line script is going to be particularly helpful.)

1 Like

The other script is an Ajax script which doesn’t rely on the definition of sidebar etc. So I guess it doesn’t matter. Many thanks for your hint about deferring scripts. I think I put that in there because I was trying to fix it, but I’ll remove it.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.