Im making a app in django which needs a accordion. This is the following HTML code
{% load static %}
{% for comp in comps %}
<script src="{% static 'main/app.js' %}"></script>
<div >
<div >
<div >
<div >
{{comp.name}}
{{comp.country}}, {{comp.city}}
</div>
<div >{{comp.descr}}</div>
<hr>
</div>
</div>
</div>
{% endfor %}
This is the css which actually hides the content. Note Ive taken out a lot of uneccessary css like font-size and colors.
.accordion .label::before {
content: ' ';
top: 50%;
transform: translateY(-50%);
}
.accordion .content {
text-align: justify;
width: 780px;
overflow: hidden;
transition: 0.5s;
}
.accordion .container.active .content {
height: 150px;
}
Finally this is javascript which is meant to add a Event Listener
const accordions = document.getElementsByClassName('container');
Array.from(accordions).forEach((accordion)=>{
accordion.addEventListener('click', function() {
this.classList.toggle('active')
})
})
The active
class isnt being added.
There might be a problem with linking the js with the HTML doc since when I run the app this is what I get in the command line.
GET /static/main/app.js HTTP/1.1
The location is definitely correct
CodePudding user response:
getElementsByClassName
returns a list of elements.
let containers = document.getElementsByClassName('container');
for(let i = 0; i < containers.length; i ) {
containers[i].addEventListener("click", function() {
this.classList.toggle('active')
})
}
CodePudding user response:
There are several points to be noticed in your source code setup, each to be handled.
Your
<script>...
tag is inside the django{% for ... %}
loop, means the same script is being loaded multiple times (depending upon size of yourcomp
). Move your<script>...
out of the loop. This will also prevent multiple declaration errors, likeaccordions has already been declared
.Your
<script>...
tag is loaded before thecontainer
class div, and the script is not waiting for document to load, so yourdocument.getElementsByClassName('container')
won't be getting anything anyway. Try adding this function call inside a document load event listener in your script, or position your script load at the bottom of your html code (preferably after thecontainer
class div).The
accordion
variable is a list, and not a singleHTMLElement
object. Therefore, theaddEventListener('click'...
won't work. Try this
...
const accordions = document.getElementsByClassName('container');
Array.from(accordions).forEach((accordion)=>{
accordion.addEventListener('click'...//rest of your code
...
})
...
- You have not included the stylesheet in html (if you have taken that part out here only then its alright).
There could be other problems as well apart from the ones I noticed from you currently provided code. But these points should help you too.