2

I need to add a class to an element on the fly. But after adding the class, all events, related to this class, work only from elements, whose classes already have been defined when the document was loaded.

Consider this example.
Text 1 has no class yet, while Text 2 does. When the button is clicked, myClass is assigned to Text 1, so both, Text 1 and Text 2, are now from class myClass.
An alert box should appear, when an element of myClass is clicked, but this event is only triggered when Text 2 is clicked. The element, whose class was already defined when the document was loaded.

<button>Add class to Text 1</button><br />
<a href="#">Text 1</a> <br />
<a href="#" class="myClass">Text 2</a>

<script>
$(document).ready(function() {
  $("button").click(function() {
    $("a").addClass("myClass");
  });
  $(".myClass").click(function() {
    alert("clicked!");
  });
});
</script>

Here is a fiddle: https://jsfiddle.net/zx8wuy97/

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • Other references on this topic: [jQuery .live() vs .on() method for adding a click event after loading dynamic html](http://stackoverflow.com/questions/8752321/jquery-live-vs-on-method-for-adding-a-click-event-after-loading-dynamic-ht/8752376#8752376) and [jQuery event handlers - what's the best method](http://stackoverflow.com/questions/9730277/jquery-event-handlers-whats-the-best-method/9730309#9730309). – jfriend00 Dec 27 '15 at 00:07

2 Answers2

1

One option would be to use event delegation. In doing so, the event is attached to a constant parent element, and the class of the descendant element is checked when the event is actually fired (rather than when the event is attached).

You should attach the event listener to a common ancestor element, but in this case I attached it to document since you didn't provide any additional markup.

Updated Example

$(document).on('click', ".myClass", function() {
  alert("clicked!");
});
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1
$(".myClass").click(function() {
   alert("clicked!");
});

// Is the same as:

$("body").on("click", ".myClass",function() {
   alert("clicked!");
});

As with dynamically loaded content, this will fix said problem.

In jQuery, how to attach events to dynamic html elements?

Community
  • 1
  • 1
Anees Saban
  • 607
  • 6
  • 11