Deka87 Deka87 - 1 year ago 47
jQuery Question

Create custom event that would work for any selector

Say I have this senseless script that changes the background color of an element when it's clicked:

$(".foo").on("change.color", function() {
$(this).css("background-color", "red");

$(".foo").click(function() {

As for now it works for the
element only due to this line:

$(".foo").on("change.color", function() { ... }

The question is how do I transform the line above to make it work with any selector I wish to use later, e.g.:

$(any_selector_here).click(function() {

Answer Source

You could add the foo className to any_selector_here

$(document).on("change.color", ".foo", function() { });


which would allow you to remove the className of specific elements, detaching event listener from those elements