Search code examples
javascriptjqueryeventsdelegation

Event data returns empty object in jquery when using "on()"


I'm trying to use event delegation using "on()" for elements that are not presently available on the page. In this case i need to pass some data to "on()" function, which is a JSON object. The code for this looks as follows:

$(document).off('click',targetElement).on('click',targetElement,eventData,function(e){
    e.preventDefault();
    e.stopImmediatePropagation();
  console.log(e.data)
  });

My issue is that when this event is triggered e.data is returned as empty object and hence m not able to consume it. I have built this code with reference API provided here: http://api.jquery.com/on/

Can anyone please guide what is going wrong here?

P.S the target element is not on page. It gets rendered on some function call.


Solution

  • Try getting target element inside the fired function (using e.target) and then consume what you want:

    $(document).on('click',function(e){
        e.preventDefault();
        e.stopImmediatePropagation();
        console.log($(e.target))
        });