Hobert Cruz
asked on
Convert addEventListener to real function..
Hi experts, how to convert the code below into real function? I need to convert the code from addEventListener to real function like, function doit(){}. Thank you!
<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>
ASKER
Hi leakim971, I attached here the codes hoping for your help. My problem here is that when I transfer data from js, then, the accordion won't work anymore. My project needs that the js will be the one to fill data in the accordion elements. Is there any ways to solve this problem? Thank you
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
.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;
}
.active, .accordion:hover {
background-color: #ccc;
}
.panel {
padding: 0 18px;
display: none;
background-color: white;
overflow: hidden;
}
</style>
</head>
<body>
<button style="height: 45px; width: 80px;" onclick="myMeds()">Transfer</button>
<br/><br/>
<button style="height: 45px; width: 80px;" onclick="doit()">Get</button>
<br/><br/><br/>
<div id="dev19">
<a class="accordion">Medicines</a>
<div id="Cx3" class="panel">
<a>Anti-biotics</a><br/>
<a>Anti-inflamatory</a>
</div>
</div>
<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>
<script>
function myMeds(){
var eDept = '<a id="Cx3" class="accordion">Medicines</a>' +
'<div ' + 'id="Vx"' + ' class="panel">' +
'<a>Anti-histamine</a>' +
'<a>Anti-virus</a>' +
'</div>'
document.getElementById("dev19").innerHTML = eDept;
return false;
}
</script>
<script>
function doit(){
var devData = document.getElementById("dev19").innerHTML
alert(devData);
}
</script>
</body>
</html>
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
but @Michel Plungjan solution is the best one
ASKER
Thank you to both of you guys, all solutions are helpful to my project. More power to both of you. God bless!
You are welcome
PS: the technique I suggested is called “event delegation”
PS: the technique I suggested is called “event delegation”
Open in new window