Bind event to a element created inside an object

I have a simple javscript object

var app = {

handle : false,

init : function() {

    var handle = document.createElement('div');

    $(handle).attr('id', 'resizegrab');


    this.handle = $(handle);

anotherfunction : function(){  


This works as I expect. I can use this.handle throughout and reference the created #resizegrab div. What I cant do though is the following outside of the class


    $('#resizegrab').on('click', function(){


nor does:

app.handle.on('click', function(){}) 

seem to work work. Any ideas how I can reference this.handle from outside of the class/object?

Try this:

$(document).on('click', '#resizegrab', function() {

You can’t use the $.click or any of the direct jQuery event bindings to elements created after they are declared. Since JS is asynchronous, app.init() is actually finishing after the event binding is declared. You can use the $(document).on event handler to bind to dynamically created elements.

On a side note, you can use jQuery to create the element as well:

var $handle = $('<div>').attr('id', 'resizegrab');
1 Like

Yay, you’re a star. Completly forgot about adding a listener to the doc ready. Ty.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.