0

This is probably an easy solution but right now I can't figure out how to make it work

$(".a").click(function () {
  if ($("#btnCollapse").css('display')!='none')
    $("#btnCollapse").click();
});

Then I tried using vanilla js, I know I am missing something....

var anchor = document.querySelectorAll(".a");   
var button = document.querySelectorAll("#btnCollapse");

function collapseNav() {
  anchor.addEventListener('click', function() { 
   button.style.display="none"
  });
  button.click();
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

4 Answers4

0

querySelectorAll() returns a collection of elements, not a single one, hence you need to loop over it. The button has an id so you can select it using querySelector() to get a single instance back.

You also have no collapseNav() function in the jQuery version so your event handler will be added on load.

Finally the logic is not the same. In the jQuery you only click the button if it's display is not none. Try this:

var anchor = document.querySelectorAll(".a");   
var button = document.querySelector("#btnCollapse");

anchor.forEach(function(el) {
  el.addEventListener('click', function() { 
    if (button.style.display != 'none')
      button.click();
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

It can be done using closure-in-loop,

var anchor = document.querySelectorAll(".a");   
var button = document.querySelectorAll("#btnCollapse");
Array.from(anchor).forEach(a => {
    a.addEventListener('click', function() {
        if(button.style.display!="none"){
            button.click();
        }
    });
});
Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Direct conversion of your "jQuery" code:

if (button.style.display != 'none')
    button.click();
oryol
  • 5,178
  • 2
  • 23
  • 18
0

querySelectorAll returns a nodelist so you need to loop through its result.

For the #bntCollapse use querySelector, it returns as single element. For elements with an id, and if you need to find many, you can use getElementById, which is faster than querySelector

To get the style, use window.getComputedStyle as it will return a style being set using external CSS as well, which element.style.display won't.

var anchors = document.querySelectorAll(".a");
for (var i = 0; i < anchors.length; i++) {
  anchors[i].addEventListener('click', function(e){
    var btn = document.querySelector("#btnCollapse");
    if (window.getComputedStyle(btn,null).getPropertyValue("display") != 'none') {
      btn.click();
    }
  })
}

Note, you can use foreach to loop the elements, though based on how, in IE, Edge and Safari it might not work, so test it thoroughly, therefore I used a for..loop for maximum browser support.

Asons
  • 84,923
  • 12
  • 110
  • 165