javascript - issue in adding events to dynamically coming elements -
this question has answer here:
doing accordion, structure follows, few divs coming dynamically, not working.
parent div
<div id="resultarea" class="accordion"> </div>
inside parent tag following tags coming dynamically.
<div class="accordion-item"> item 1 <div class="type"></div> </div> <div class="data"> data related item 1 </div> <div class="accordion-item"> item 2 <div class="type"></div> </div> <div class="data"> data related item 2 </div>
below javascript
$(function($) { var allaccordions = $('.accordion div.data'); var allaccordionitems = $('.accordion .accordion-item'); $('.accordion > .accordion-item').click(function() { if($(this).hasclass('open')) { $(this).removeclass('open'); $(this).next().slideup("slow"); } else { allaccordions.slideup("slow"); allaccordionitems.removeclass('open'); $(this).addclass('open'); $(this).next().slidedown("slow"); return false; } }); });
but not working when items data coming dynamically, if static page working. please me solve
static 1 in jsfiddle find below
try use event-delegation
on dynamically created elements,
$('.accordion').on('click','.accordion > .accordion-item',function() {
full code:
$('.accordion').on('click','.accordion > .accordion-item',function() { if($(this).hasclass('open')) { $(this).removeclass('open'); $(this).next().slideup("slow"); } else { allaccordions.slideup("slow"); allaccordionitems.removeclass('open'); $(this).addclass('open'); $(this).next().slidedown("slow"); return false; } });
Comments
Post a Comment