I\'m dynamically creating a div. I\'d like to add a onClick() event to it.
How do I add an onClick as in
Event delegation is the right way to do it and @Tushar has the answer for you. But, if you were after something like this:
$('', { class: 'something', id: 'btnHome' onClick: 'return true' })
Then, you may do:
$('', {
'text': 'new',
'class': 'something',
'id': 'btnHome'
}).on({
'click': function() { alert ("clicked") }
});
Demo@Fiddle
As squint suggests in one of the comments below, you could also use click
as an attribue just like text
or id
as the following.
$('', {
'text': 'new',
'class': 'something',
'id': 'btnHome',
'click': function() { alert ("clicked") }
});