.on() not binding to futre elements jQuery -
i'm using .on()
bind button element click event, bind correctly elements loaded in present when new elements added won't bind them ideas ?
$('article#content').on('click', 'button', loaddata); function loaddata() { var moretxt = $(this).parent().find('section.hidden') var txt = moretxt.is(':visible') ? 'read more' : 'hide'; $(this).text(txt); moretxt.slidetoggle('slow'); }
jsfiddle = http://jsfiddle.net/jrtmc/
the delegate form of .on()
allows attach handler parent element exist, , filter events against click originates. allows set handler once, , not worry whether have attached new objects or not.
in form, element(s) call .on()
must not deleted after attach handler. in case $('article#content')
must exist when call on()
, must parent of button
care (which may or may not exist), , must not deleted/created/recreated after call .on()
.
i suspect #content
being dynamically generated. (if not, have other issues, because button referencing .parent()
, #content
) if article
dynamic, need attach handler permanent parent. can use body
, very heavy-handed, click in body have filtered through handler. additionally, can't have more 1 of same id, need use class (.content
), instead:
$('body').on('click', '.content button', loaddata);
instead, find permanent parent , use that:
$('#parentofarticles').on('click', '.content button', loaddata);
Comments
Post a Comment