Why when the page loads the event is triggered?

Asked

Viewed 66 times

0

It’s just a test, wanted when I clicked on the table to show me a message, but when the page is loaded the event is triggered, wanted to know why this is happening

My code

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <table id="t">   
           <tr><td id="t1">one</td></tr>   
           <tr><td id="t2">two</td></tr>   
        </table>

        <script type="text/javascript">
            document.querySelector('#t').addEventListener('click', alert('ola mundo'), false);
        </script>
    </body>
    </html>

1 answer

6

Diogo, the second parameter of the method addEventListener expects a function that will be executed every time the event is triggered. By passing only the alert('ola mundo') this excerpt is interpreted and executed by returning void, that is, nothing. This interpretation occurs as soon as your line, ...addeventlistener..., is interpreted by the browser. For this reason it sends the alert as soon as the page is loaded.

To solve the problem:

<table id="t">   
  <tr><td id="t1">one</td></tr>   
  <tr><td id="t2">two</td></tr>   
</table>
<script type="text/javascript">
  document.querySelector('#t').addEventListener('click', function() { alert('ola mundo') }, false);
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.