Reputation: 836
$(document).ready(function(){
$('#add').click(function(){
$('#list-area').append("<div class='list-item'><div class='box'><div class='dot'>✓</div></div></div>");
$('.box').click(function(){
$(this).children('.dot').toggle(200);
});
});
});
Here's a jsfiddle link to all my code.
This is a rudimentary replica of a checklist that I'm building. Here's how it works (or supposed to work):
-Click the " + " to add an item. (This works fine.)
-Click the green box to check-off the item, or click it again to uncheck it...
...This misbehaves. What I want is that when a '.box' is clicked, it's respective '.dot' child element should toggle display once. But what happens is, the toggle repeats depending on how many items there are.
To clearly see my problem, add 5 items and click on their green boxes. The top will toggle 5 times, the next will toggle 4 times, etc.
Why does this occur? How can I adjust the code to make it behave the way I explained?
Upvotes: 0
Views: 793
Reputation: 3968
Also you can check jQuery.on()
$(document).ready(function () {
$(document).on('click', '.box', function () {
$(this).children('.dot').toggle(200);
});
$('#add').click(function () {
$('#list-area').append("<div class='list-item'><div class='box'><div class='dot'></div></div></div>");
});
});
Upvotes: 0
Reputation: 700820
Add the event handler to only that element that you create:
$(document).ready(function(){
$('#add').click(function(){
var dot = $('<div>').addClass('dot').html('✓');
var box = $('<div>').addClass('box').append(dot);
$('#list-area').append($('<div>').addClass('list-item').append(box));
box.click(function(){
dot.toggle(200);
});
});
});
Upvotes: 2