event.toElement.id always undefined when I trigger event click

avatar
9    2 months ago

 am newbie to html and java-script ,trying to fire a click event when page load finished

$(document).ready(function(event){
    $("#london").click(function(event){
       openCity(event,'London');
    });

    $("#london").trigger('click'); //this is automatic click

});

This click is working.But in my function

function openCity(evt, cityName) {
   var id = evt.toElement.id; //id is undefined only when click event triggered
}

id is undefined only when click event triggered,when normal click it contains value.

Answers { 1 }
avatar
2 months ago

Instead of toElement you need to use target.

For more info I'd suggest to read What is the difference between Event.target, Event.toElement and Event.srcElement?

function openCity(evt, cityName) {
  var id = evt.target.id; //id is undefined only when click event triggered
  console.log('id: ' + id);
}

 $("#london").click(function(event){
    openCity(event,'London');
});

$("#london").trigger('click'); //this is automatic click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button type="button" id="london">london</button>