2

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.

Community
  • 1
  • 1
Andy
  • 1,422
  • 5
  • 27
  • 43
  • 1
    You're not appending the link after the jQuery has run? In that case you should use on() (http://api.jquery.com/on/) instead of click(). – Filip Dec 01 '11 at 17:51
  • 1
    @Filip Yup, or use `.click()` only if the element is available per Shankar's answer. – Greg Pettit Dec 01 '11 at 17:55

1 Answers1

5

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();
    });
  });
});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124