I'm dynamically creating a div. I'd like to add a onClick() event to it.
How do I add an onClick as in <div class="something" id="btnHome" onClick="return true">
to this?
abc.append(
$('<div />', { class: 'something', id: 'btnHome' })
);
EDIT:
I'm looking for an answer something like this
$('<div />', { class: 'something', id: 'btnHome' onClick: 'return true' })
I'm dynamically creating a div. I'd like to add a onClick() event to it.
How do I add an onClick as in <div class="something" id="btnHome" onClick="return true">
to this?
abc.append(
$('<div />', { class: 'something', id: 'btnHome' })
);
EDIT:
I'm looking for an answer something like this
$('<div />', { class: 'something', id: 'btnHome' onClick: 'return true' })
Share
Improve this question
edited Apr 19, 2015 at 9:53
Becky
asked Apr 19, 2015 at 9:48
BeckyBecky
5,5859 gold badges43 silver badges78 bronze badges
4
|
3 Answers
Reset to default 10Use event delegation
:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
For dynamically added elements use parent to add event to the added elements.
$(staticParentSelector).on('click', '.something', function () {
// Event Handler Code here
});
You can also use document
, but this costs performance
$(document).on('click', '.something', function () {
// Event Handler Code here
});
see jQuery Docs for on
Event delegation is the right way to do it and @Tushar has the answer for you. But, if you were after something like this:
$('<div />', { class: 'something', id: 'btnHome' onClick: 'return true' })
Then, you may do:
$('<div/>', {
'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.
$('<div/>', {
'text': 'new',
'class': 'something',
'id': 'btnHome',
'click': function() { alert ("clicked") }
});
You can use delegated events so add to your jquery code:
$(document).on('click','#btnhome',function(){'do something here'});
You can use document or any other parent element that is already in the DOM
....}).on("click",function() {return true;});
or delegate like in the answer – mplungjan Commented Apr 19, 2015 at 9:50$('<div />', { class: 'something', id: 'btnHome' onClick: 'return true' })
– Becky Commented Apr 19, 2015 at 9:52