0

Someone posted this answered with a link to a non-solution. It hasn't been answered.

I have js writing html from json using the same classes to display content. for example:

 <!-- item 1 -->
 <div class="item">
   <div class="name">The Name 1</div>
   <div class="hidden">hidden info</div>
 </div>

 <!-- item 2 -->
 <div class="item">
   <div class="name">The Name 2</div>
   <div class="hidden">hidden info</div>
 </div><!-- item -->

With .hidden having a 'none' property in css.

My goal is to click on .name and have .hidden toggle on/off, I can only make this work if I manually put the html in the doc using:

$('.item').click(function(){
  $(this).find('.hidden').toggle(500);
  });

but this doesn't work if I use js to add the html. I also tried:

$('.item').on( "click", function() {
   $(this).find('.hidden').toggle(500);
   });

and

$(document).on( "click", ".item", function() {
   $(this).find('.hidden').toggle(500);
   });

but when the js writes the html, it just doesn't work. Any ideas? I tried searching in vain but maybe I'm not searching for the right solution, any help would be greatly appreciated.

Damien
  • 11
  • 3
  • You have to add the event handlers to the elements that were added via javascript. – Brian Jan 10 '18 at 18:55
  • I don't understand what you mean by "manually". Please provide a detailed step by step explanation of what is happening. Is the `$(".item).click(...)` running **after** you have added the HTML to the page with JS? – zero298 Jan 10 '18 at 18:59
  • Have you tried "$(document).on('click','.item',function(){$(this).find('.hidden').toggle(500);}) – Hanif Jan 10 '18 at 19:03
  • By manually, I mean just adding the html to the document instead of having the js write it. – Damien Jan 10 '18 at 21:01
  • I tried using using "$(document).on('click','.item',function(){$(this).find('.hi‌​dden').toggle(500);}‌​)" and "$('.item').on('click', function(){$(this).find('.hi‌​dden').toggle(500);}‌​)" but I'm running into the same issue, it doesn't work if js writes the the html. – Damien Jan 10 '18 at 21:02

0 Answers0