Reputation: 282
I'm learning jQuery/javascript and have a rather basic question. Why doesn't this work? Thanks in advance.
<script type="text/javascript">
$(document).ready(function () {
$('<div/>', {
id: 'foo',
text: 'Does not work'
}).appendTo('body'); });
</script>
<script type="text/javascript">
$("#foo").click(function () {
alert('Success'); });
</script>
Upvotes: 1
Views: 1327
Reputation: 23250
It doesn't work because the second script section will execute before $(document).ready
is fired. Thus it will be trying to attach the onclick handler to an element that doesn't exist yet.
You can make it work by either attaching the click()
event to the element as you add it:
$(document).ready(function () {
$('<div/>', {
id: 'foo',
text: 'Does not work'
})
.appendTo('body')
.click(function() {
alert('Success');
});
});
or by using on()
:
$('document').on("click", "#foo", function() {
alert('Success');
});
Upvotes: 2
Reputation: 6536
You gotta place all of that in a $(document).ready().
So:
$(document).ready(function () {
$('<div/>', {
id: 'foo',
text: 'Does not work'
}).appendTo('body');
$("#foo").click(function () {
alert('Success'); });
});
Upvotes: 1