How to trigger custom event with jQuery?

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.


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");
}