1

for example if I click on the add+ 9 times, I'll have 10 boxes. but after that, Only if A click the last box, it will hide. (I want hiding the specific box by clicking on that box). by the way after click (and desappering) the last box, the other boxe wont hide in any way whats my problem?

$(document).ready(function(){
    $("#add").click(function(){
        $(".test:last").clone().insertAfter(this);
    })
    $(".test").click(function(){
        $(this).hide("slow");
    })
})

<div id="add">ADD+</div>
<div class="test" style="border:1px solid black; width:70px; height:25px;">
    box
</div>

3 Answers 3

4

Because you're only hooking up the one that exists when the document loads. Change

$(".test").click(function(){
    $(this).hide("slow");
})

to

$(".test").live('click', function(){
    $(this).hide("slow");
});

click is for hooking up events to elements that already exist. Using live, you can be more speculative and say "hook up this event for any that already exist, and any I add later that match this selector." There's also delegate which can be useful if you want the functionality of live, but one for descendants of a particular element.

Details:

Sign up to request clarification or add additional context in comments.

Comments

3

Use .clone(true) instead of just .clone() to copy the event handlers as well.

Example: http://jsfiddle.net/hQ5Qc/


I'd also add that you may want to change the selector from this:

$(".test:last")

to this:

$(".test:visible:last")

so if you hide the last box, you're not cloning one that was already hidden.

Example: http://jsfiddle.net/hQ5Qc/2/

1 Comment

That's another way to go, yeah.
0
$(document).ready(function(){
    $(".test").click(function(){
         $(this).hide("slow");
    })

    $("#add").click(function(){
         $(".test:visible:last").clone(true).insertAfter(this);
    })
})

added :visible per comment suggestion

1 Comment

not different, sometimes you will get many answers to easy question that are all the same in functionality

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.