Search code examples
javascriptjqueryevent-handlingeventtrigger

Find a dynamical generated element by listening to a custom event (JavaScript)


I have a list whose li are generated dynamicaly via AJAX:

<ul>
  <li id="hello"></li>
  <li id="world"></li>
  <li id="helloWorld"></li>
</ul>

I also have a global var in my script like this:

var world = 'world';

I want, on document ready, as soon as the list gets loaded, to find the li item with the same id as my global var:

$('ul').find('#' + world);

I can't use a conventional .on() event listener here since there is no other event to trigger it, except for the end of the loading itself.

So my next step was to trigger a custom event in my loading script:

$('ul').trigger('loadingDone');

And then listen for it:

$('ul').one('loadingDone', theFunctionThatDoesTheSearch );

Problem is, this failed and it completely ignored any of the generated elements.

I know that a possible solution would be to run these operations inside the success method of the ajax call, but the current architecture of the app I'm building doesn't allow for that. (I can and do trigger the event inside the success AJAX method, I just cant do the search there)

Basically what I am asking for are alternative solutions for allowing the loading script to let me know when it is done and ways to filter trough the generated content without doing the filtering inside the loading script itself.


Solution

  • $(document).on("customevent","ul",function(){
    console.log("event triggered from inside the ajax success handler");
    });
    
    $.ajax({
        url:'/echo/json/',
        success:function(){
        $('div').append("<ul><li>asd</li></ul>");
            $("ul").trigger("customevent");
        }
    });
    

    http://jsfiddle.net/xp7sr/2/