'How does adding or removing classes from html elements affect the onclick and other similar functions attached to those elements?
I have some simple code. I am using jQuery. I have two elements with a particular class a assigned to them. One of them is also assigned class b1.
Class b1 has an onclick property attached to it.
Now I place a button which when clicked tried to remove the class b1 from all elements, but even after that I see the click function is still active.
Can someone please explain ? I have my code on jsfiddle.
I observed that only CSS properties get added. The JavaScript events tied up to those elements do not come into place.
<body>
<table>
<tr>
<td class="a b1" id="cell1">Cell 1</td>
<td class="a b2" id="cell2">Cell 2</td>
</tr>
</table> <a href="#" id="click1">Remove B1 </a>
<br/>
</body>
<script>
$(document).ready(function() {
$(".b1").click(function () {
alert("B1");
});
$("#click1").click(function () {
alert("removed b1");
$(".a").removeClass('b1');
alert("removed b1 from all elements. ");
//even after executing this statment - the onclick still remains active.
});
});
</script>
Solution 1:[1]
$(".b1") returns elements and .click() attaches an event handler to the elements themselves. The selector isn't "dynamic". What you're looking for is event delegation:
$('table').on('click', '.b1', function() {
...
});
This attaches the event handler to the table element, which in turn delegates it to the child elements that match that selector.
Solution 2:[2]
You're attaching the onclick event handler to elements that match the selector. The selector just grabs the collection of elements and then applies it to them, you can't apply an event handler to a class.
You could do something like this to only run the handler when the class is present.
$(".b1").click(function () {
if ($(this).hasClass('b1')) {
alert("B1");
}
});
Solution 3:[3]
How the JavaScript works in this instance is once the document is ready, it adds the listeners to the appropriate DOM objects. (So in this case, it adds the click listener to all the tags that have class b1 at the point that the document has finished loading). Even if you change the class after the document has finished loading, the listener still looks for the original tags.
In order for a function to be run only on the currently-selected elements, try the on() function
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Blender |
| Solution 2 | Daniel Imms |
| Solution 3 | Aaron_H |
