Ways to include external JavaScript in an HTML document along with CSS styling

Check out this code snippet in HTML with embedded JavaScript. I'm trying to externalize the JS file, but it's not functioning as expected when I do so. How can I resolve this issue and ensure that the element moves upon clicking when the script is external?

<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
</script>

Answer №1

To include an external JS file in your HTML file, make sure to place the script tag within the head section of the HTML file.

<head>
  <script src="file.js" defer></script>
</head>

Answer №2

Make sure to include the script tags after all elements (before the closing </body>) or enclose them in a load handler:

window.addEventListener("DOMContentLoaded", function() { 
  var acc = document.getElementsByClassName("accordion"); 
  .....
})

It is also advisable to delegate from the accordion container instead of using a loop

document.getElementById("accordionContainer").addEventListener("click", function(e) { 
  const tgt = e.target.closest(".accordion"); 
  if (tgt) tgt.classList.toggle("active"); 
  tgt.nextElementSibling.classList.toggle("hide", !tgt.classList.contains("active"));
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is my Javascript XMLHttpRequest onreadystatechanged event not triggering?

I am facing an issue with my html file and a .txt file stored in the same directory on a webserver. In the html file, I have the following code: <html> <head> <script> window.onload = function() { receiveMessage(); } function recei ...

Create a rectangle when the mouse is pressed down

Creating a zoomable and pannable canvas in Fabric.js was easy, but now I am facing an issue with accurately drawing a rectangle on each mousedown event. The problem arises when the canvas is transformed from its original state, making the coordinates inacc ...

Enable vertical scrolling on the second row of a table while keeping the first row fixed as the table header (CSS)

While embedding the Ace Editor in a Chrome popup window, I encountered a challenge. My goal was to keep the first row of text always visible at the top while allowing the rest of the Editor to fill the screen. However, there is an issue with a vertical scr ...

Unable to display Bootstrap 5 modal

I am currently in the process of constructing a basic webpage that includes a navigation bar and a table. The table rows are being dynamically generated through a simple JavaScript script that fetches data asynchronously from a database. I opted to utilize ...

Updates in dropdown events when options data has been modified

Hey there, I'm wondering about dropdown events. Let's say I have two dropdowns. When a selection is made in the first dropdown, all options in the second dropdown are replaced with new ones. For example, let's say the first dropdown has thes ...

Scrollable Flexbox Container

In my flex container, I am attempting to create another flex container that will scroll content if it exceeds the screen size. Here is the code I have so far: <Box sx={{ m: 'var(--Content-margin)', p: 'var(--Content-pa ...

Converting JavaScript CanvasRenderingContext2D states array into a serialized format

Looking for a way to serialize a canvas' state in order to save it to a database for later restoration. Want to store the data as an object rather than a bitmap file. I've tried using .save() and .restore() on the context object, but they only m ...

What is the process for creating a customized object using Serialized format?

In order to convert a few serialized form elements into a JSON object, I created a function. However, when the fieldName is included in the JSON object, it appears as "fieldName" instead of the actual field name such as "PositionId" or "Series". Although ...

Preserving the true IP address when initiating cross-domain requests

Initially, I tried creating a reverse proxy using Express to enable forwarding requests from localhost:3000/request to somesite.com/request. Here is the code snippet I used: var request = require('request'); app.get('/', function(req, ...

Display the entire paragraph when hovering over it

Is there a way to make the entire paragraph appear on hover instead of just showing parts of it? I am building a website on Weebly for a school project and my knowledge is limited. I tried using the following code, but it only displays some of the content ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...

Tips for sizing a div based on the dimensions of an image

Looking to Achieve: I have a PNG image of a shirt with a transparent background that I want to place on top of a colored square. I want the shirt in the image to stand out over the edges of the square, creating a visually appealing effect. The image's ...

The generation of React Native Jest coverage results may vary depending on how an ES6 module is exported

I am working with a React Native button component that consists of its own index.js and styles.js files. The content of styles.js is as follows: import { StyleSheet } from "react-native"; export default StyleSheet.create({ container: { borderRadius ...

javascript design pattern - achieving unexpected outcome

In the code snippet provided, the variable a is turning out to be undefined. Are you expecting it to display the parameter value passed in the parent function? function test(a) { return function(a) { console.log('a is : ' + a); // Ou ...

Can you identify the target of the term "this" in the upcoming JavaScript code?

DISCLAIMER: I am inquiring about a specific instance of this, not its general purpose. Please refrain from quick Google responses or copied answers (: The code snippet below demonstrates JavaScript/jQuery: var req = {}; function getData() { var from ...

Utilizing Ajax in PHP to Upload Files

I'm encountering an issue while attempting to upload a file and send it via AJAX. The error message I am receiving is as follows: Notice: Undefined index: xlsFile in Here is the code snippet: HTML FORM : (this form is within a Modal Popup) <f ...

Unlocking the Power of jQuery's toggle Method for Dynamic Functionality

For my project, I require numerous jQuery toggles to switch between text and icons. Currently, I am achieving this by using: $("#id1").click(function () { //Code for toggling display, changing icon and text }); $("#id2").click(function () { //Same co ...

Why does the styling on my <a> tags in the footer only take effect when I apply padding to the form above?

It seems that when styling the <a> tag for the list in the footer, no changes occur even if correctly applying the style. However, adding padding to the form in the main part of the code causes the links in the footer to show the change. To see this ...

Navigating to external URLs using a Form-based approach in .NET Framework

Is it possible to direct to an external website using a URL as a Command Argument? I attempted to redirect to facebook.com, but it resulted in http://localhost:58709/www.facebook.com%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20% ...

Using conditional CSS in React/Next.js

While using Next.js, I have implemented conditional rendering on components successfully. However, I am facing an issue where the CSS styles differ between different components. Code 1: import React from "react"; import Profile from "../../ ...