CaptSaltyJack
CaptSaltyJack

Reputation: 16035

How do I make a recursive jQuery function?

I'm trying to make a jQuery plugin that will take a square, put three squares in it, and then within those three squares, place three more smaller squares. I don't need or want full code as this is my own problem to figure out, but I can't figure out how to make a jQuery plugin call itself, e.g.:

(function($){
    $.fn.squares = function( type ) {
        var recursionDepth = 1;

        return this.each(function() {
            var $this = $(this);

            if (++ recursionDepth > 3) {console.log('rec lim');return;}
            // put div.squares in $this
            $('.square', $this).squares();
        });
    };
})(jQuery);

Upvotes: 1

Views: 4472

Answers (1)

tvanfosson
tvanfosson

Reputation: 532435

Use a helper function that does the actual work and takes the depth as a parameter. Call it from the plugin main method with depth 1 (or 0) and recurse over it incrementing the depth as you go until you get to the desired depth.

Untested:

(function($){ 
    $.fn.squares = function( type ) { 

        return this.each(function() {  
            doSquares($(this),1);
        });

        function doSquares($square,depth) { // adds three squares to the current square and recurses over each to the appropriate depth
             for (int i = 0; i < 3; ++i) {
                var $newSquare = // add square to current square and return jQuery of the new square
                if (depth < 3) {
                    doSquares($newSquare,depth+1);
                }
             }
        }
    }; 
})(jQuery);

Upvotes: 3

Related Questions