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.