10

I'm attaching a custom event handler to the body in jQuery's ready method.
Afterwards I immediately trigger the custom event but nothing seems to happen.

$(function(){
    $("body").on("test", function(){ alert("test triggered"); }
    $("body").trigger("test");
}
Axel
  • 3,331
  • 11
  • 35
  • 58
JJK
  • 179
  • 1
  • 2
  • 9

2 Answers2

6

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.

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • 4
    Sure you can. Executing `$("body").trigger("test");` in the console will work. Why wouldn't it work? `$` is a global variable. – Šime Vidas Jun 20 '13 at 00:35
  • My apologies on the syntax error. Didn't know that an event listener wouldn't hear an event happening outside of its closure. Thanks! – JJK Jun 20 '13 at 00:36
4

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");
}
Robert Waddell
  • 879
  • 7
  • 15