Andy M. Andy M. - 3 months ago 17
Javascript Question

Conversion from JS to JQuery

Hi I am having problem in converting the code from JS to JQuery
It is a sample code from W3School to create a dropdown button.

Can anyone help.

// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("myBtn").onclick = function() {myFunction()};

/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {

var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}

Answer

The code is very simple to understand if you try jQuery.

// Execute the code when the document is ready.
$(document).ready(function () {
  /* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
  function myFunction() {
    // This one removes the class "show" from the matched set of elements.
    $(".dropdown-content").removeClass("show");
    // This one toggles the class "show" on the matched set of elements.
    $("#myDropdown").toggleClass("show");
  }

  // Get the button, and when the user clicks on it, execute myFunction
  $("#myBtn").click(myFunction);
});

I don't think this is a problem with conversion of code. I strongly believe that W3Schools has given you a wrong way of using repeated id values.