javascriptgoogle-chromeonclickdom-eventsevent-delegation

Why does Logging onclick event turns out to be undefined in chrome?


    <ul onClick='pop()'>
    <li id="1">1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
   </ul>

    function pop(event) {
    let ul = document.getElementsByTagName('ul')[0];
    console.log(window.event); //Valid mouseEvent
    console.log(event) // Undefined
}

So the question is that why does logging event results to be undefined whereas window.event has a valid value ? Browser - chrome


Solution

  • Here's how to handle the event in an efficient way. You didn't pass any event to pop.

    function pop(event) {
      let ul = document.getElementsByTagName('ul')[0];
      console.log(window.event); //Valid mouseEvent
      console.log(event) // Undefined
    }
    
    document.getElementById("yourid").addEventListener('click', pop);
    <ul id="yourid">
      <li id="1">1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
    </ul>