Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does vanilla js addEventListener not work in WordPress?

I checked other questions which are similar but they are all having mistakes in the code.

This is a different case.
The jQuery part in this code is working fine but if I work with the vanilla js, the click event is not triggered and no console error detected.
The script is run at the bottom of the body after the elements are loaded.

  //jQuery - this works
  const openSearchButton = $(".js-search-trigger");
  openSearchButton.on("click", () => console.log("hello"));
  
  //Vanilla JS - this does not
  const openSearchButton = document.querySelector(".js-search-trigger");
  openSearchButton.addEventListener("click", () => console.log("Hello"));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

querySelector only acts on the first matching element:

const openSearchButton = $(".js-search-trigger");
openSearchButton.on("click", () => console.log("jquery"));

//Vanilla JS
const openSearchButtonTwo = document.querySelector(".js-search-trigger");
openSearchButtonTwo.addEventListener("click", () => console.log("vanilla"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="js-search-trigger">Button one</button>

<button class="js-search-trigger">Button two</button>

From comments, you have another (hidden) element on the page with the same class, so need to use querySelectorAll instead.

jQuery automatically iterates over the whole list of results for you, but in vanilla you have to do that explicitly:

const openSearchButtons = document.querySelectorAll(".js-search-trigger");

[...openSearchButtons].forEach(button => {
  button.addEventListener("click", () => console.log("all vanilla"));
})
<button class="js-search-trigger">Button one</button>

<button class="js-search-trigger">Button two</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading