Ajouve
Ajouve

Reputation: 10049

JQuery event in javascript object

I have a javascript object

function A()
{
    this.ini = function()
    {
        $('#test').html('<button id="click" >Hi</button>');
    }    

    $('#click').on('click',function(){
        alert('Hi');
    });
}

http://jsfiddle.net/G2MUE/1/

But I have a problem, the event onClick is not used.

Thanks for your help

Upvotes: 0

Views: 159

Answers (4)

GautamD31
GautamD31

Reputation: 28773

You dont need to put it in initializeation.Try like

function A()
{    
    $('#test').html('<button id="click" >Hi</button>');             
    $('#click').on('click',function(){
       alert('Hi');
    });
}
A();

See this DEMO

Upvotes: 0

Martin
Martin

Reputation: 471

function A()
{
    this.ini = function()
    {
        $('#test').html('<button id="click" >Hi</button>');
    }    

    $(document).on('click', '#click', function(){
        alert('Hi');
    });
}

http://jsfiddle.net/G2MUE/7/

Upvotes: 3

Manoj Nama
Manoj Nama

Reputation: 639

Try this

$(document.body).on('click', "#click" ,function(){
    alert('Hi');
});

You are attaching handler before the element is in the DOM.

Upvotes: 6

Jason P
Jason P

Reputation: 27022

You're trying to bind a handler to an element that doesn't exist. Try something like this:

http://jsfiddle.net/pdT24/

function A() {
    this.ini = function () {
        $('<button id="click" >Hi</button>')
            .click(clickfn)
            .appendTo('#test');

    }

    var clickfn = function (e) {
        alert('Hi');
    };
}
var a = new A();
a.ini();

An alternative would be event delegation with on():

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

Upvotes: -1

Related Questions