-2

I want to hide/show the ul element when I click on the h3 tag. I tried some examples, maybe I am missing something.

My sample code:

$('#gallery').append('<h3 id="' + idx + '" >' + item.title._content + '</h3><ul style="display:none;" class="photos grp' + idx + '"></ul>');

$('h3#'+idx).click(function () {
   $(this).next('.photos.grp'+idx).toggle();
});
Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
Alex
  • 11
  • 6

3 Answers3

1

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

.delegate( selector, eventType, handler )

// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );

You can use jQuery delegate events handler which can be used on your dynamic added elements.

e.g. In your case

$('#gallery').append('<h3 id="' + idx + '" >' + item.title._content + '</h3><ul style="display:none;" class="photos grp' + idx + '"></ul>');

$('h3#'+idx).on('click', function() {
   $(this).next('.photos.grp'+idx).toggle();
});

OR

$('h3#'+idx).delegate('#gallery', 'click', function() {
   $(this).next('.photos.grp'+idx).toggle();
});

Here, #gallery is your Parent element of all child elements.

Ashwin Parmar
  • 3,025
  • 3
  • 26
  • 42
0

Because you are dynamically You should use this

var id = 'h3#'+idx;
$('#gallery').on('click',id,function(){
    $(this).next('.photos.grp'+idx).toggle();
})
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

Try this :

$('h3#'+idx).on('click',function () {
       $(this).next('.photos.grp'+idx).toggle();
  });

Because you are appending html from jquery then use `.on()` shown above.
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
  • maybe i'v something miss in my explanation, please look my code on jsbin, i'v try use on, trigger and a lot of other stuff.. – Alex Aug 06 '14 at 15:55