-1

The idea of the class is to create X squares on the screen, and change their colors randomly.

Here it is:

function Blocks() {
    var Size = 0;
    this.setSize = function(inputSize) {
            Size = inputSize;
    };

    this.createEnvironment = function() {
            var Block, prevBlock, i;
            for (i = 0; i < Size; i++) {
                    Block = document.createElement('div');
                    Block.className = 'block';
                    Block.id = i;
                    prevBlock = document.getElementsByTagName('div')[i];
                    prevBlock.parentNode.insertBefore(Block, prevBlock);
            }
    };

    this.randBlock = function() {
            return document.getElementsByTagName('div')[Math.floor(Math.random() * Size)];
    };

    this.randColor = function() {
            var Chars = '0123456789ABCDEF'.split('');
            var randColor = '#';
            for (var i = 0; i < 6; i++) {
                    randColor += Chars[Math.floor(Math.random() * Chars.length)];
            }

            return randColor;
    };

    this.goCrazy = function() {
            var Block = this.randBlock();
            Block.style.background = this.randColor();
            var t = setTimeout('this.goCrazy()', 1000);
    };
}

Here is the usage:

var object = new Blocks();
object.setSize(10);
object.createEnvironment();
object.goCrazy();

css code:

.block is 30x30 px, dispaly inline-block.

and before calling the class, there is a blank div tag, for reference where to create the blocks.

All the code above, displays only one colored block, instead of that all will be colored, and change rapidly.

Chrome's warning:

Uncaught TypeError: Object [object DOMWindow] has no method 'goCrazy'
2
  • 1
    don't use the reserved word object Commented Jan 21, 2012 at 20:07
  • Not related to the problem but you should also avoid Uppercased variable names as these denote Class names in most OO languages, as you can see in the syntax highlighting. Commented Jan 21, 2012 at 20:21

1 Answer 1

2

Timer-Functions (setTimeout) are executed within their own scopes. Wrapping the code into a closure should work:

var t = setTimeout(function () { _self.goCrazy(); }, 1000);

Have a look at: http://jsfiddle.net/TimWolla/BHeZR/ for a demo.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.