0

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', '');
});
1
  • Where do you set the class from "expanded" back to "contracted"? Commented Apr 23, 2014 at 22:00

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.