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');

    $(handle).appendTo(app);

    this.handle = $(handle);
},

anotherfunction : function(){  
    this.handle.hide();
}

}

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

$(document).ready(function(){
    
    app.init();    

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

});

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() {
    alert('test');
});

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');
$handle.appendTo(app);
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.