Andy
Andy

Reputation: 1432

JQuery FadeOut/Remove

This is a follow on from a post here > How to "fadeOut" & "remove" a div in jQuery? - but we're two years on and rather than dig that up it makes sense to make a new post.

I've played around with it and this works (inline JQuery)

<a onclick='$("#alert_top").fadeOut(300, function(){ $(this).remove(); });' class="alert_topClose">Link</a>

removing the div "alert_top". But the inline link is untidy.

Attempting to achieve the same result, this doesn't work (JQuery + link)

$(".alert_topClose").click(function(){
    $("#alert_top").fadeOut(300, function(){
        $(this).remove();
    });
});

with the link

<a class="alert_topClose">Link</a>

Any help as to why would be greatly appreciated. I can't see what the problem is.

Upvotes: 2

Views: 1591

Answers (1)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Make sure you are executing the above code in $(document).ready() or $(). If the element is not available when jQuery tries to fetch it, it cannot attach the event handler. Try this

$(function(){
  $(".alert_topClose").click(function(){
    $("#alert_top").fadeOut(300, function(){
      $(this).remove();
    });
  });
});

Upvotes: 5

Related Questions