简体   繁体   中英

How do I remove a dynamically added element after 5 seconds?

I'm making a simple game where users should click flies to remove them from the screen. The user should not click the cat when it drops, and I'm hoping to make the cat gif disappear (remove itself from the DOM) after 5 seconds.

I apologize if this has been answered before. I'm having a hard time solving this as my experience is very limited. This is my first question/post ever. Thanks for any and all feedback :)!

$('.square').each(function(i){
    if (($('.square').eq(i)).has(".cat")){
        setTimeout(function(){
            $('.square').eq(i).find('img').remove();
    }, 5000);       
};

^this is the code I tried to write... the .square class are the squares that make up the table like grid of divs... and the .cat class refers to an image dropped.

The problem is multiple cats can be dropped on the screen at the same time.

I need the page to recognize when a cat is dropped, set a timeout for 5 seconds when that occurs, and then remove that particular cat from the page after 5 seconds.

Thanks for the help :)!

var randomize = function (x) {return Math.floor(Math.random()*x)};

var startFunk = function(){
    setTimeout(function(){
        $('.square:empty')[randomize(($('.square:empty').length))].innerHTML = dropArray[randomize(dropArray.length)];
        startFunk();
    }, 500);
};

May help

$('.square').each(function(i){
    if ($(this).find('.cat').length > 0){
        $(this).find('.cat').delay(5000).fadeOut(0, function(){
            // change ..^... with img 
            $(this).remove();
        });
    }
});

DEMO Here

var startFunk = function () {
    setTimeout(function () {
        var sqr = $('.square:empty')[randomize(($('.square:empty').length))];
        sqr.innerHTML = dropArray[randomize(dropArray.length)];
        sqr.has('.cat').delay(5000).empty();
        startFunk();
    }, 500);
};

And get rid of the $('.square').each(function(i){... part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM