1

I have two buttons and want to use eventlisteners before buttons declaration. But first alert does not shows. How to fix that?

 <body>
<script>
    window.onload = function() {
    const bt1 = document.getElementById('btn1');

    bt1.addEventListener('click', function (event) {
        alert('bt1 case');
    });
    }
</script>
<script>
    window.onload = function() {
        const bt2 = document.getElementById('bt2');
        bt2.addEventListener('click', function (event) {
            alert('bt2 case');
        });
    }
</script>
    <button id='bt1'> bt1 </button>
    <button id ='bt2'> bt2 </button>

</body>
person
  • 11
  • 1
  • 1
    Does this answer your question? [Add two functions to window.onload](https://stackoverflow.com/questions/16683176/add-two-functions-to-window-onload) – Rashomon Mar 24 '21 at 17:52

1 Answers1

0

That's because you're replacing the first listener with the second. Try using addEventListener instead. You also had a typo on line 4: you spelled bt1 as btn1

<body>
  <script>
    document.addEventListener('DOMContentLoaded', (event) => {
      const bt1 = document.getElementById('bt1');

      bt1.addEventListener('click', function(event) {
        alert('bt1 case');
      });
    });
  </script>
  <script>
    document.addEventListener('DOMContentLoaded', (event) => {
      const bt2 = document.getElementById('bt2');
      bt2.addEventListener('click', function(event) {
        alert('bt2 case');
      });
    });
  </script>
  <button id='bt1'> bt1 </button>
  <button id='bt2'> bt2 </button>
</body>
Rojo
  • 1,941
  • 1
  • 7
  • 24