Skip to content Skip to sidebar Skip to footer

Repeating Elements With Jquery

I'm sure this is going to be obvious to the right person, but how can I repeat an element with jQuery? Esentially I want jQuery to repeat an inline element an infinite number of ti

Solution 1:

http://jsfiddle.net/gRTTJ/

Key line:

$("#repeating").append($(".foobar").clone());

Although if you want it infinitely, it will be an infinite loop (obviously) and not be too useful.

A slightly more reasonable version that runs infinitely:

functionrepeat()
{

   $("#repeating").append($(".foobar:first").clone());
}

$(function () {

    setInterval(repeat, 1000);
});

Solution 2:

while(true) {
  $('#infinity-repeat').append('some text');
}

But that code will crash your browser. Better idea is to do it countable times.

Solution 3:

Here's what I came up with:

setInterval(function(){
    var length = $(".hi").length;
    if(length >= 10){
        // don't append
    } else {
        $("<div class='hi'>text</div>").appendTo("body");
    }
}, 1);

A couple things are happening here. First (besidessetInterval()), we're getting the length of elements with class hi. Of course, at first it will be 0. Then we're checking if it's greater than or equal to 10. If it is, we're not appending it. Otherwise, we continue appending.

This goes on until there are 10 elements with the class hi on the page. Of course, I just limited it to give you a glimpse at how it works. If you just continued appending with setInterval() it would look like this (and this one doesn't crash your browser).

Solution 4:

I'm sure you want to clone something finitely but that aside here is an example of a plugin type of duplication / clone:

Given this html:

<div id='duplicateme'>Duplicate This</div>

And the plugin itself:

$.fn.duplicate = function(count, withDataAndEvents) {
    var tmp = [];
    for (var i = 0; i < count; i++) {
        $.merge(tmp, this.clone(withDataAndEvents).get());
    }
    returnthis.pushStack(tmp);
};

Can be called in two ways:

// duplicate item 5 times
$('#duplicateme').duplicate(5).appendTo('#duplicateme');

// duplicate item 5 times along with attached events
$('#duplicateme').duplicate(5, true).appendTo('#duplicateme')

Solution 5:

var lastAppended = $("<span>some text</span>");
var repeatingArea = $("#repeating");
repeatingArea.append(lastAppended);
while (lastAppended.position().top < repeatingArea.height()) {
    lastAppended = lastAppended.clone();
    repeatingArea.append(lastAppended);
}

That should fill the repeating area. If the repeating area can have scroll-bars, then the test in the while loop gets a bit more complicated, and you'll need to re-call this whenever the user scrolls, but the idea is the same.

EDIT: here's a jsfiddle http://jsfiddle.net/6FW4n/3/ note that if the height isn't set, it'll be an infinite loop

Post a Comment for "Repeating Elements With Jquery"