Al-Punk
Al-Punk

Reputation: 3659

jQuery toggle on sublements populated by Ajax

I have some json file which populates the page with some info. On the populated elements I need to run a toggle operation but I cannot retrieve the subelement in jquery.

function() {
  $.getJSON( "/pathto/glossar.json", function( data ) {
    var items = [];
    $.each( data, function( key, val ) {
      items.push( "<dt>" + key + "</dt>\n\r<dd id='" + key + "'>" + val + "</dd>\n\r\n\r" );
    });
    $( "<dl/>", {
      "id": "glossar",
      html: items.join( "" )
    }).appendTo( "#main-container" ).on(
        $("dt").click(function() {
            $(this).children().toggle()
        })
        //$('dd').hide()  
    );
  });
}

The generated DOM elements are

<dl id="glossar">
<dt>KEY</dt>
<dd id="KEY">Bla Bla Value</dd>
..
</dl>

I need to toogle on the dd values once the dt is clicked. Looks like the jquery .on does not fetch DDs in this case!? Is there a need for a second .on on dt-s?

Upvotes: 1

Views: 161

Answers (2)

Irvin Dominin
Irvin Dominin

Reputation: 30993

Since you are adding dynamically your elements you have to use event delegation with jQuery on:

Attach an event handler function for one or more events to the selected elements.

Ref:

The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element. In Internet Explorer 8 and lower, a few events such as change and submit do not natively bubble but jQuery patches these to bubble and create consistent cross-browser behavior.

If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

You can define one handler in document.ready, so outside your ajax call like:

$("body").on("click", "#main-container dt", function () {
    $(this).siblings("dd").toggle();
});

For the HTML provided the dd element it's a sibling of dt not a children, so I changed the selector accordingly.

Demo: http://jsfiddle.net/IrvinDominin/EFb4X/

Upvotes: 1

Snehal S
Snehal S

Reputation: 875

Try this, in getjson function write following code,

$( "<dl/>", {
  "id": "glossar",
  html: items.join( "" )
}).appendTo( "#main-container" );

And in document ready i.e after $.getjson write your click

$("dt").click(function() {
    $(this).children('dd').toggle();
});

Upvotes: 1

Related Questions