Mustang31
Mustang31

Reputation: 282

Selecting New Element with jQuery

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

Answers (2)

Jivings
Jivings

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

Dhaivat Pandya
Dhaivat Pandya

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

Related Questions