user3608209
user3608209

Reputation: 45

jquery: hide each div of same class separately when user clicks div to close?

I have multiple divs of the same class which act as notification boxes, and each one fades in one after the other, one by one using jQuery. I also have a div called 'close_box' which acts as a close button so when a user clicks this the div will close/hide using jQuery. The problem I am having is, because the divs have the same class, when a user clicks the 'close_box' div this should close each div separately. Instead whats happening is all three divs are suppose to have a close button showing 'close_box' div, but only the third box is showing this and only the third box is closing while the other two boxes are not showing the 'close_box' div and can't be closed.

Is there a way I can use parent or some similar idea to close each div separately and can someone please show me where I am going wrong and how to do this? thanks

<div class="noti_box"><div class="noti_text"><h4>You have 11 New Messages</h4></div><div class="close_box"></div></div>

<div class="noti_box"><div class="noti_text"><h4>You have 11 New Notifications</h4></div><div class="close_box"></div></div>

<div class="noti_box"><div class="noti_text"><h4>6 Matters Needing Your Attention</h4></div><div class="close_box"></div></div>

<script type="text/javascript">
$('.noti_box').each(function(i) {
    $(this).hide().delay(i * 1500).fadeIn(1500);

    $('.close_box').on('click', function() {
        $(this).closest('.noti_box').fadeOut();
    }).appendTo(this);
});
</script>

Upvotes: 0

Views: 669

Answers (1)

VisioN
VisioN

Reputation: 145478

Just separate these two actions and remove appendTo(this):

$('.noti_box').each(function(i) {
    $(this).hide().delay(i * 1500).fadeIn(1500);
});

$('.close_box').on('click', function() {
    $(this).closest('.noti_box').fadeOut();
});

What you posted is just the wrong interpretation of my example from your previous question.

DEMO: http://jsfiddle.net/F39TV/4/

Upvotes: 4

Related Questions