Jack Bird
Jack Bird

Reputation: 207

Jquery fadeOut with this selector

I am trying to make an element disappear when clicked, the elements are dynamic.

$("#toast-container").on("click", "div.toast", function() {
    $(this).fadeOut("fast", function() {
         $(this).remove();
    });
}); 

I have tried the code with just $(this).remove() and it works but using fadeOut it doesn't. I have no idea why and it looks absolutely fine to me

Upvotes: 2

Views: 131

Answers (3)

Sarower Jahan
Sarower Jahan

Reputation: 1495

I have a easy solution.

HTML

<div id="toast-container">
   <div class="toast">
      Click Me
   </div>
</div>

jQuery

$("div.toast").click(function(){
    $(this).parent("#toast-container").fadeOut('slow');
    // run your another event.
})

Check my live demo on jsfiddle

Upvotes: 4

Aram Rafeq
Aram Rafeq

Reputation: 41

well when adding elements dynamically to DOM tree i think your events may register at creation of the page but when you add an element dynamically you should use another jquery function which is called delegate see the documentation

Upvotes: 1

Korgrue
Korgrue

Reputation: 3478

What is this?

"div.toast"

If your div class is "toast", it should just be ".toast" (it will work with the div.toad, but syntactically, this is not really correct.

That said, your function works fine when I drop it in a fiddle. Are you certain that you are not getting any console errors perhaps related to another feature/function? Check your console.

Upvotes: -2

Related Questions