Question

jQuery Click function isn't working on first child of li becomes '.contracted' as on jsFiddle

<ul class="clearfix">
  <li class="contracted">
    <a href="#">
      <span>L1<b>: Recognize a digit represents 10 times the value</b></span>
    </a>
  </li>
  <li class="">
    <a href="#">
      <span>L2<b>: Recognize a digit represents 10 times the value</b></span>
    </a>
  </li>
</ul>

I tried to move click function at bottom as well. But it isn't working. Full working example is given in jsFiddle.

$('.contracted').click(function () {
  $(this).parent().attr('class', 'expanded');
  $('ul.expanded li.activeLesson').attr('class', 'selected');
  $('ul.expanded li:not(.selected)').attr('class', '');
});
Was it helpful?

Solution

Your $('.contracted').click(...) code will bind a click handler to any elements with that class at the moment that code runs - this will not automatically work on other elements that have the class added later. If you want it to work on any li element that has the contracted class at the time of the click use a delegated event handler set up via .on():

$('ul').on('click', 'li.contracted', function() {
   ...
});

This binds the click handler to all ul elements, but then when a click occurs jQuery checks if the clicked item is a descendant of the ul which matches the selector in the second argument and only calls your function if it does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top