Home > front end >  Convert jQuery Script to plan JS for bootstrap nav bar drop down collapse on top of iframe
Convert jQuery Script to plan JS for bootstrap nav bar drop down collapse on top of iframe

Time:10-01

I'm trying to convert a jQuery script to pure JS. This script is to fix an issue on a site of mine were I have a nav bar with drop downs with an iframe on the rest of the screen.

Without this script the downdowns don't collapse when anywhere in the iframe is clicked. The jQuery works but I cant get the JS only working and don't know much about JS

$(window).on("blur", function() {
  $(".dropdown").removeClass("show"), 
  $(".dropdown-menu").removeClass("show"),
  $(".dropdown-toggle").attr("aria-expanded", !1).focus()
});
window.blur(), 
document.getElementsByClassName('dropdown').classList.remove('show'), 
document.getElementsByClassName('dropdown-menu').classList.remove('show'), 
document.getElementsByClassName('dropdown-toggle').getAttribute("aria-expanded", !1).focus;

CodePudding user response:

You didn't provide the html, so it's not as easy to answer this question.

ES6 way

window.onblur = () => {
  const
    removeClass = (el, className) => el.classList.remove(className),
    dropdowns = document.getElementsByClassName('dropdown'),
    menus = document.getElementsByClassName('dropdown-menu'),
    togglers = document.getElementsByClassName('dropdown-toggle')

  for (const d of dropdowns) removeClass(d, 'show')
  for (const m of menus) removeClass(m, 'show')
  for (const t of togglers) t.getAttribute('aria-expanded', false).focus
}
.dropdown {
  display: none;
}

.dropdown.show {
  display: initial;
}

.dropdown-menu {
  display: none;
}

.dropdown-menu.show {
  display: initial;
}
<div class="dropdown-toggle" aria-expanded="true">
  toggler
</div>
<div class="dropdown show">
  <div class="dropdown-menu show">
    menu
  </div>
</div>

Old way

window.onblur = function () {
  function removeClass(el, className) {
    el.classList.remove(className)
  }

  // When calling `getElementsByClassName, you get collection of elements
  // So you can't call `classList` method on it
  var dropdowns = document.getElementsByClassName('dropdown')
  var menus = document.getElementsByClassName('dropdown-menu')
  var togglers = document.getElementsByClassName('dropdown-toggle')

  // You have to iterate over found elements
  for (var i = 0; i < dropdowns.length; i  ) removeClass(dropdowns[i], 'show')
  for (var i = 0; i < menus.length; i  ) removeClass(menus[i], 'show')
  for (var i = 0; i < togglers.length; i  ) togglers[i].getAttribute('aria-expanded', false).focus
}
  • Related