Search code examples
javascripthtmladdeventlistener

addEventListener not working as it should


I have problem with adding event listener into JS...If i connect button with onclick attribute its working but if I delete it in HTML and try to add eventListener('click', myFunction), its not working. And btw its a simple dropdown button.

In following example in button i deleted onclick="myFunction" and added this - >

JavaScript:

document.getElementById("btn").addEventListener('click', myFunction);

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

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');
      }
    }
  }
}
 

HTML:

<button id="btn" class="dropbtn">RECEPT</button>
<div id="myDropdown" class="dropdown-content">
  <ul>
    <li>-5 jaja</li>
    <li>-0.2l mleka</li>
    <li>-100g slanine</li>
    <li>-200g brasna</li>
    <li>-10g putera</li>
    <li>-50g sira</li>
    <p class="recipeInfo">Kuvati na laganoj vatri i ostaviti da se krcka 5 minuta</p>
  </ul>
</div>

I dont know what is the problem nor solution...Any help?


Solution

  • You are probably trying to access the DOM elements before they are ready. Try placing your Javascript code inside a DOMContentLoaded listener:

    document.addEventListener("DOMContentLoaded", function(event) { 
        // put your javascript code here
    });
    

    This will guarantee that your Javascript code will have access to all DOM elements. Read more at $(document).ready equivalent without jQuery