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/