Javascript to jQuery

jquery

#1

I'm new to jQuery but my assignment is to make an accordion menu. I completed the assignment in JS because that's what I'm comfortable with. But now I need to translate it into jQuery. It is intimidating me! Any help would be appreciated.
Here's my JS file:

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.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    }
}

#2

Welcome to the forums, @rebekahray564. I formatted your code for you, but in the future, to make it easier for us to read, you can format it yourself by adding three backticks (`) on the line before the code, and three backticks on the line after the code. Or you could just highlight your code that you pasted into the post, and select the </> icon that you see just above the edit area.


#3

Hi,

Not tested, but this should get you started:

var $acc = $(".accordion");

$acc.on("click", function(){
  $(this).toggleClass("active");
  var $panel = $(this).next();
  if ($panel.is(":visible")) {
    $panel.hide();
  } else {
    $panel.show();
  }
});

#4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.