Eduard
Eduard

Reputation: 3576

click() event jquery

So I have this code which is called in a print_info() function after a AJAX Request;

'print_info' : function(message,type) {
        $('.load').hide();
        $('<div>'+message+'</div>').insertAfter('#loader').addClass('autoHideBox '+type).fadeIn("slow").delay(2000).fadeOut("slow", function() { $(this).remove(); });
    },

As you may see, the div fades in an out in a matter of seconds, my problem is, even if I'm adding this code :

.click(function() { $(this).fadeOut("slow", function() { $(this).remove(); }); } )

The div wont fadeOut / remove at all. Can you clear this one ? Because I'm a bit confused regarding this matter.

Regards, Duluman Edi


Later edit:

I got it working with .on("click", callback), but though, fading it out and removing it in the callback just wouldn't work.

So, in order to get it working so you can do whatever you need to do in the callback of the on("click", just add before .on() , stop(true,true).on("click",callback);

'print_info' : function(message,type) {
        $('.load').hide();
        $('<div>'+message+'</div>')
            .insertAfter('#loader')
            .addClass('autoHideBox '+type)
            .fadeIn("slow")
            .delay(2000)
            .fadeOut("slow", function() { $(this).remove(); })
            .on('click', function() {
                $(this).stop(true,true).fadeOut("slow", function() { $(this).remove(); })
            });
    },

Upvotes: 2

Views: 195

Answers (3)

Matt Garriott
Matt Garriott

Reputation: 362

This works for me:

$(document).ready(function () {
     var div = $('<div>This is a test</div>');
     div.insertAfter('#test');
     div.click(function () { 
       div.fadeOut("slow", function() { div.remove(); }); 
     });
   });

Upvotes: 0

Eric
Eric

Reputation: 10658

You should use .live('click', function for dynamically added content.

Upvotes: 0

Kristian
Kristian

Reputation: 21840

I think the problem is that .click is only attachable to elements that were loaded originally on page load.

Since you create the element right then, it isn't being properly attached to the click event. Try instead using .on('click', callback) because that can be added to anything that is dynamically created after page load.

http://api.jquery.com/on/

Upvotes: 2

Related Questions