How to trigger custom event with jQuery?
14,749
Solution 1
Firstly you have a syntax error
$(function(){
$("body").on("test", function(){
alert("test triggered");
}); < ---- Missing this
$("body").trigger("test");
});
Secondly you cannot trigger the event from the console , as $(function() {});
forms a closure and you will not have access to any of the methods inside them
For it to work like you are expecting , put a debug point in your script file and then try to trigger the event. It works now as the events are in scope.
Solution 2
It looks like your code is not formatted correctly. Check your debug console to confirm.
You can try this:
$(function(){
$("body").on("test", function(){
alert("test triggered");
});
$("body").trigger("test");
}
Author by
JJK
Updated on June 05, 2022Comments
-
JJK almost 2 years
I'm attaching a custom event handler to the
body
in jQuery'sready
method.
Afterwards I immediatelytrigger
the custom event but nothing seems to happen.$(function(){ $("body").on("test", function(){ alert("test triggered"); } $("body").trigger("test"); }
-
zod almost 11 years.on - Attach an event handler function for one or more events to the selected elements. what is the event here?
-
Musa almost 11 years@dementic please don't change the code in edits
-
Šime Vidas almost 11 years@zod "test", it's a custom event.
-
Kirby over 8 yearsrolled question back to original state to reflect the root problem
-
-
Šime Vidas almost 11 yearsSure you can. Executing
$("body").trigger("test");
in the console will work. Why wouldn't it work?$
is a global variable. -
JJK almost 11 yearsMy apologies on the syntax error. Didn't know that an event listener wouldn't hear an event happening outside of its closure. Thanks!