Combining CSS and JS files for accordion list - experiencing issues when used separately

Recently, I've been trying to create an accordion list and stumbled upon some code (HTML, CSS, and JS) on www.w3schools.com. When I have the code all in one document and run it as a single .html file, everything works perfectly. However, when I split it into three separate files and link the CSS and JS files in my HTML file, the dropdown functionality stops working. As someone who is new to web development, I would greatly appreciate any help or explanation on why this might be happening! Thank you in advance.

Below is the original code all within one document:

<!DOCTYPE html>
<html>
<head>
<style>
button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ddd;
}

button.accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: "\2212";
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}
</style>
</head>
<body>

<h2>Accordion with symbols</h2>
<p>In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.</p>
<button class="accordion">Section 1</button>
<div class="panel">
  <p>TEXT 1</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>TEXT 2</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>TEXT 3</p>
</div>

<script>
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }   
  }
}
</script>

</body>
</html>

And here's the separated HTML file linking the CSS and JS files:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="./mystyling.css">
    <title>Page TItle</title>
</head>
<body>
<script src="./myjavascript.js"></script>

<h2>Accordion with symbols</h2>

<p>In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.</p>
<button class="accordion">Section 1</button>
<div class="panel">
      <p>TEXT 1</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>TEXT 2</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>TEXT 3</p>
</div>
</body>
</html>

In my separate JS and CSS files, I simply copied and pasted the contents of the respective files from the original code.

Answer №1

Just a quick tip: Make sure to place your JavaScript link at the bottom of the body section in your HTML code. It's important for your HTML to load before the JavaScript does:

<script src="./myjavascript.js"></script>
</body>

Another important point to remember is that Mozilla Developer Network is a more reliable and informative resource compared to W3 Schools. It's better to refer to MDN for accurate information.

Do you know where your JavaScript and CSS files are located? If possible, could you provide the code for those files as well?

In order to debug more effectively, try opening the HTML file in your browser and use the developer tools to identify any errors you may encounter (if there are any). You can press option+command+j on Mac or control+shift+j on Windows, or simply right-click and select inspect element.

Answer №2

The way you're referencing the stylesheet in the directories with

<link rel="stylesheet" href="./mystyling.css">
seems to be causing errors in certain directories.

<link rel="stylesheet" href="mystyling.css">

If the CSS file is in a folder, use

<link rel="stylesheet" href="folder/mystyling.css">

When it comes to the JavaScript file, it's recommended to place it at the end of the body tag

<script src="myjavascript.js"></script>
</body>

If your code is short, consider putting it directly in the same file within a script tag

<script> 
//Your code
</script>

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

How can we incorporate "req.getParameter" within a "for loop" to store data in the database based on the user-defined quantity provided in another servlet?

Currently, I am working on a system where teachers have the ability to edit exams they have created. However, an issue arises when trying to save the questions and answers, as it depends on the number of questions in the exam. While requesting variables f ...

The Uglify task in Grunt/NPM is having trouble with this particular line of JavaScript code

Whenever I execute grunt build, Uglify encounters a problem at this point: yz = d3.range(n).map(function() { return k.map(x -> x[1]); }), An error message is displayed: Warning: Uglification failed. Unexpected token: operator (->). I have recentl ...

only a single backdrop filter can be in use at any given moment

Experimenting with backdrop-filter in Chrome 76. I'm working on a menu with 2 divs, each with a backdrop-filter applied. The first div is displaying the filter effect perfectly, but the second one isn't. Interestingly, when I remove the filter fr ...

What is the reason for the getter not being able to retrieve the value

I am experiencing an issue with a getter that returns an array of objects. The challenge I face is that I need to display past and current warnings in separate components. The getter currently only retrieves the current warning and ignores any past warnin ...

I'm having trouble figuring out how to remove an unexpected blank space that appears after the <li> element in a basic drop-down menu code. Can

Why is the browser (Mac Chrome + Firefox) adding extra space after my simple CSS drop-down menu where I have a hidden sub-menu? Check out the code below: <ul> <li>Option Zero</li> <li>Option One Is Longer</li> &l ...

Is it feasible to develop an asynchronous function in Node.js that executes concurrently?

My objective is to simultaneously execute the longRunnigTask and quickTask functions: function longRunnigTask() { return new Promise((resolve) => { console.log('longRunnigTask started'); for (let i = 0; i < 999999999; i+ ...

What is the best way to implement this header style with code?

I came across this design from a potential client recently, even though we didn't end up working together. I thought it would be a good exercise to try coding the design for practice purposes. Just to clarify, this is not my original design and I have ...

Z-Index not functioning as expected

I've been trying to position my <h1> header on top of a light div with a background image called light.png. I used Z-index to stack them and added position:relative, but for some reason, the <h1> is not showing above the <div class=ligh ...

Tips for choosing the remaining items in a multiple selection process

In my HTML form, I have a multi-select field that contains categories and the corresponding items within each category. My goal is to allow users to select individual courses or select an entire category (identified by values starting with "cat_") in orde ...

Alternative image loading in a figure element

I'm currently in the process of putting together an image gallery using Angular 4.3.0, where images are displayed as background images within figure elements rather than img tags. The images are initially resized to smaller dimensions before being use ...

How can you create an event that is focused on options using Material-UI's Autocomplete feature?

This is regarding Material-UI's Autocomplete feature. I am looking for a way to track which autocomplete choice the user is currently focused on, whether it be through hovering over with the mouse or using keyboard arrows - before any actual selection ...

The event on the full calendar is stuck in place and will not budge

function moveEvent(event, delta, revertFunc) { console.log(event.title + " has been moved to " + event.start.format()); var page = '../include/UpdateCalendarEvent.php'; $("#dialog") .data('start', event.start.format ...

Issue with displaying ng-repeat data in AngularJS tbody

I am experiencing an issue with using ng-repeat inside a tbody element. Here is the code snippet that is causing trouble: <tbody> <tr ng-repeat="group in groups"> <td>{{ group.name }}</td> </tr> </tbody> Wh ...

Incorporating conditional statements within a loop

I'm racking my brains over this issue, can you lend a hand? Currently, I am extracting data from a website. The .MyElement containers on the site store either gif or jpg URLs that I need to retrieve. In my node.js app, I am utilizing a Cheerio-base ...

Refreshing an HTML table using instance variables from a C# class (utilizing jQuery and AJAX)

Explore <script type="text/javascript"> $(document).ready(function () { $("#viewDetails").click(function () { $.ajax( { type: "POST", url: '@Url.Action("GetDetail", "ControllerName")' ...

Changing the Values of Variables in an npm Package within SvelteKit

I have been working on a SvelteKit component library where I define variables for components like background-color and font-family in a CSS file. Inside the ./dist/index.js file of my library, I export the CSS using `import './main.css'`. When in ...

search engine optimized for easy input via keyboard

I have successfully incorporated AJAX search functionality into my project, inspired by this example here. The unique feature of this implementation is the ability to navigate through search results using the TAB key. The structure of my search results tab ...

Has anyone experienced challenges with _POST data getting blocked on a hosting server provided by Godaddy?

Utilizing a form processor known as JotForm, I have encountered an unusual issue. When attempting to print all POST data, I am faced with an empty array, specifically when the page is hosted on GoDaddy. Strangely, while hosting it locally on localhost, no ...

What is the best way to trigger an AJAX function every 15 seconds?

As part of my web application, I have implemented a JavaScript function that is triggered by the <body onload> event. Within this function, there is a while loop that continuously iterates until it receives the desired response from a PHP page. Unfo ...

Customize hoverIntent to support touch events on mobile devices

Hello everyone. I've encountered an issue with hoverintent.js, a jQuery plugin that handles mouseOver events differently than usual. I am facing constraints where I can only modify the JavaScript of this plugin, but I need it to be compatible with to ...