0

I have the following function, which is invoked immediately and binds a click event to elements.

(function (window, $, undefined) {
    var methods     = {},
    selector = $('.selector');

    methods.init = function () { 
        selector.find('> .section').on('click', function (e) {
          alert('hey');
        }
    }

    if (selector.length > 0) {
        methods.init();
    }

}(window, jQuery));

I needed it to also bind elements that had been added dynamically, so I changed to this:

var modules = modules || {};
modules.stuff = (function (window, $, undefined) {
    var methods     = {},
    selector = $('.selector');

    methods.init = function () {
        selector.find('> .section').on('click', function (e) {
          alert('hey');
        }
    }

    if (selector.length > 0) {
        methods.init();
    }


    return methods;

}(window, jQuery));

And then added dynamic elements, then called modules.stuff.init(); I can see that the init function is ran but the click events don't fire?

DavidB
  • 2,566
  • 3
  • 33
  • 63

1 Answers1

3

You need to use the delegated signature of the on() method. Try this:

methods.init = function () {
    selector.on('click', '> .section', function (e) {
        alert('hey');
    }
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339