I am currently struggling to get a function working with a button that has an onclick event to toggle a class. Please can you review the code and help me understand why it is needing two clicks and how to fix it.
function dropdownbuttonclick(element) {
let coll = $(".dropdown");
for (let i = 0; i < coll.length; i++) {
//coll[i].addEventListener("click", function () {
$(this.firstChild).toggleClass('fa-chevron-down fa-chevron-up');
var content = this.nextElementSibling;
//console.log(content);
if (content.style.height === "auto") {
content.style.height = "75px";
}
else {
content.style.height = "auto";
}
//});
}
}
if (row.description.length > 50) {
return "<div width='100%' style='min-height:100px;" + backgrnd + "'><button type='button' class='dropdown' onclick='dropdownbuttonclick(this)'><i class='fa fa-solid fa-chevron-down'></i></button><div class='content' style='margin:20px;'>" + title + "</div></div>";
}
I have tried to change the onclick event but I am not sure how to fix.
3
Answers
The issue in your code is because
this
will refer to thewindow
as the function was invoked via aonclick
attribute.As you’re gone to the effort of including jQuery in the page, you should use that to attach your event handlers unobtrusively, and also to set the classes on the elements.
In addition, it’s better practice to use CSS to update the UI, so simlpy toggling a class to set the height of the element would be a better approach. Try this:
Finally, note that any CSS/styling should be placed in an external stylesheet, not in the HTML.
I’m guessing with the first click it adds both classes (
fa-chevron-down
andfa-chevron-up
) and the second, takes both classes out. Try separating them:Hope this helps !
You could solve the issue by replacing
this
with theelement
that the function takes as argument. Furthermore you should usefirstElementChild
instead offirstChild
.Working example:
(i simplified your example a bit)