0

How can I acceess objects(divs) that were dynamically generated. I mean DIVS that were not present in output when $(document).ready(function() started.

If I do:

$('#click_me').click(function() {
    $('#container').append('<div id="clicker2">can you click on me?</div>');
});

$('#clicker2').click(function() {
    alert('hurray, it works');
});

the clicker2 won't work

How can I fix it? I'm intent to create more than one dynamically. and I want to assign Jquery actions to themt too.

3 Answers 3

3

.click() functions that aren't working on spans or divs that are added later, you'll need to use .live()

$("#clicker2").live("click", function(){
  # do stuff to spans currently existing
  # and those that will exist in the future
});
Sign up to request clarification or add additional context in comments.

1 Comment

well my actions get duplicated as well !!!! :( when I do APPEND and then assign action to it. next time I do append and assing action when action is fired up.. it runs twice
1

Create the div explicity and assemble its attributes and events before you append it.

var $div = $('<div />').append('can you click on me?').attr('id', 'clicker2').click(function() {
alert('hurray, it works');
});
$('#container').append($div);

Comments

0

Just put the click binding inside the first click function:

$('#click_me').click(function() 
{
    $('#container').append('<div id="clicker2">can you click on me?</div>');
    $('#clicker2').click(function(){  alert('hurray, it works');   });
});

As you have it, the binding is being called, but there is no "div#clicker2" to bind to the second function.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.