-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();
});
8

3 Answers 3

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.

0

Because you are dynamically You should use this

var id = 'h3#'+idx;
$('#gallery').on('click',id,function(){
    $(this).next('.photos.grp'+idx).toggle();
})
1
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.
1
  • 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 6, 2014 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.