Deka87 Deka87 - 3 months ago 7
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() {
$(this).trigger("change.color");
});


As for now it works for the
.foo
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() {
$(this).trigger("change.color");
});

Answer

You could add the foo className to any_selector_here

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

$(selectors).addClass("foo");

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

$(any_selector_here).removeClass("foo");