0

I got this function which adds a div each second. it then moves across the screen, and I'd like for it to remove the divs once they're outside the screen. Is it possible to "attach" such a timer to the divs as I create them?

   function deployRandom(){     
        $(".bottomEvents").append("<div class='floatingDiv'>hello world</div>")
        $(".floatingDiv").animate({ 
            marginLeft: "+=250px",
        }, 1000 );      
    }

2 Answers 2

2

The main idea is that: You must know if your div get out of the range("out of window size").

First you must know window width:

$(window).width();

than you must know your div position to the left

currentDiv.position().left + currentDiv.width()

and than if your div out of range you must hide it.

Here small example: https://jsfiddle.net/RomanGroovyDev/pyzuLtzd/3/

Sign up to request clarification or add additional context in comments.

Comments

1

You can append every created div to an array and check for theirs position with a unique dispatcher timer:

var divsArray = [];

function clearOutsideDivs()
{
    var newDivsArray = [];

    for (var i=0; i<divsArray.length; ++i)
    {
        var currentDiv = divsArray[i];
        var currentDivMarginLeft = parseInt(currentDiv.css('margin-left'), 10);

        if (currentDivMarginLeft > $(window).width())
            currentDiv.remove();
        else
            newDivsArray.push(currentDiv);
    }

    divsArray = newDivsArray;
}

function deployRandom(){
    var generatedDiv = $("<div class='floatingDiv'>hello world</div>");
    $(".bottomEvents").append(generatedDiv);
    divsArray.push(generatedDiv);

    $(".floatingDiv").animate({ 
        marginLeft: "+=250px",
    }, 1000, clearOutsideDivs);   
}

jsFiddle example here.

1 Comment

Sorry for the late response. Incredible answer, and very appreciated. Works perfectly :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.