2

I have a code chunk of html:

<div id="chunk-1" class="chunk">  
    <div class="chunkText">Text<div>  
    <button class="addChunk">Click Me</button>  
</div>

<script>

$(".addChunk").click(function(){create_chunk(this.parentNode)})

function create_chunk(after_this){
    $(after_this).after(chunk_html)
    var i = 0
    $("div.chunk").each(function(){$(this).attr('id', "chunk-" + i++)})
    }

</script>

Now, this works, but only for the .chunk that is statically rendered on the page. When I press the button a second chunk appears, but that button does not work. If I add the html for two or more chunks to be rendered, each one works, but the buttons for the chunks it creates do not. What should I do?

1

3 Answers 3

3

The event handler in the below line attaches the click event to the element matching the selector when you add the handler.

$(".addChunk").click(function(){create_chunk(this.parentNode)})

you can use the live handler to do this. the following code will solve your problem

$(".addChunk").live('click'. function(){create_chunk(this.parentNode)});
Sign up to request clarification or add additional context in comments.

2 Comments

@jAndy - The question says another chunk is added...so what would you delegate on? #chunk-1 doesn't work here, you need a higher ancestor.
Ohh well, for some reason I just assumed OP wants to duplicate an item within the div.
2

Use the "live" jQuery function.

$(".addChunk").live('click'. function(){create_chunk(this.parentNode)});

The problem is that you're binding to a single element. The "live" option will monitor the document for any clicks on elements that have the ".addChunk" class.

Comments

2

replace

.bind()

with

.live()

or even better use

.delegate()

which is in your case:

$('#chunk-1').delegate('.addChunk', 'click', function(){create_chunk(this.parentNode);})

furthermore, go to www.jquery.com and read the documentation.

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.