Search code examples
javascriptjqueryeventstargeting

Unable to get the event target property of a named function


In the fiddle linked below there's some example code I need to troubleshoot. I've simplified it a bit from the original code (didn't write) for demo purposes in the fiddle.

$(document).ready(function(){
    $("ul").children().each(function(i){
        $(this).click(function(){
            var indexItem = i; 

            if(indexItem == 0){
                 displayId();                                  
            }
            if(indexItem == 1){
                displayNode();
            }
            if(indexItem == 2){
                displayNodevalue();
            }
       });
    });
})
function displayId(event){
   // below returns undefined not what I want
   // var $listID = jQuery(this).attr("id"); 
   var $listID = event.target.id;
    alert($listID);
}

function displayNode(event){
    var listNodename = event.target.nodeName;
    alert(listNodename);
}

function displayNodevalue(event){
    var listValue = event.target.nodeValue;
    alert(listValue);
}

How do I get the event.target properties for these items? The console displays:

Uncaught TypeError: Cannot read property 'target' of undefined

I've googled various possible solutions below. They are good but I'm not finding the answer.

How to pass the event object to a named function

Getting the ID of the element that fired an event

https://api.jquery.com/event.target/

If I've missed the answer in those threads, please let me know. Seems this question should be answered somewhere, but I'm having trouble locating it. If not, I'd appreciate some help telling me what is wrong with this code and how to get the event target. Thanks.

FIDDLE LINK


Solution

  • You need to pass the event object as a parameter

    $(document).ready(function () {
        $("ul").children().each(function (i) {
            $(this).click(function (e) {
                var indexItem = i;
    
                if (indexItem == 0) {
                    displayId(e);
                }
                if (indexItem == 1) {
                    displayNode(e);
                }
                if (indexItem == 2) {
                    displayNodevalue();
                }
            });
        });
    })
    

    Demo: Fiddle


    Also try

    $(document).ready(function () {
        var fns = [displayId, displayNode, displayNodevalue]
        $("ul").children().click(function (e) {
            var indexItem = $(this).index();
            fns[indexItem] ? fns[indexItem](e) : '';
        });
    })
    

    Demo: Fiddle