0

So, there are two important details to this question:

  1. its inside the scope of document ready's callback function
  2. the element that the event is attached to does not actually exist in the DOM

Here's a visual representation of the scenario

$(document).ready(function() {
    $('#myNonExistentElement').on('click', function() {
        //do something
    });
});

Is it possible to programatically trigger that click event (via console or something else) under those circumstances?

Kristian
  • 21,204
  • 19
  • 101
  • 176

2 Answers2

2

I think the simple answer is no.

There are two cases which might, however, fit with your question:

1) If you just want to execute the event handler code, use a named function (instead of an anonymous function) and call it whenever you need to.

2) If you want to bind a click handler to an object that does not yet exist in the DOM but you know will in the future, you can use code like:

$(document).ready(function() {
  $('body').on('click', '#myNonExistentElement', function() {
    //do something
  });
});

See the section about delegated events at http://api.jquery.com/on/

Noah Freitas
  • 17,240
  • 10
  • 50
  • 67
1

If you try to bind an event to an element that doesn't exist via jQuery (or at the very least, .on) no new event will be bound.

Sample case here.

*event code stolen from here because I'm lazy.

Community
  • 1
  • 1
Snuffleupagus
  • 6,365
  • 3
  • 26
  • 36