user2199660
user2199660

Reputation:

Why Does my JQuery Script Crash My Page?

JSFiddle: http://jsfiddle.net/WA4eD/4/

JQuery:

$('h3').each(function() {
    var colors = [],
        availColors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'],
        randomColor;
    $('span', this).each(function() {
        do {
            randomColor = availColors[Math.floor(Math.random()*availColors.length)];
        }
        while ($.inArray(randomColor, colors) != -1)

        colors.push(randomColor);

        $(this).css('color', randomColor);
    });
});

This script you see is what I am trying to implement into my website, however all attempts I have made to implement have failed.

View Source: view-source:http://rafflebananza.com/new-website/index.html

Where the script currently is on my page is not the only place I have tried implementing, however all has resulted in the same result.

Feel free to use my script, what it does is if you have a bunch of h3 tags and the characters inside are in span classes, it will randomize the colour, different outcome on page load.

Upvotes: 2

Views: 393

Answers (2)

Zabed Akbar
Zabed Akbar

Reputation: 537

You are trying to access an out of bound array index in the random color generator while multiplying the generated random number by array length. So if the random generator returns any value greater than .9, you are multiplying it by array.length and thus trying to access an array element that does not exist. I believe that is causing the crush.

Fix the following line by using a range from 0 to array.length.

 randomColor = availColors[Math.floor(Math.random()*availColors.length)];

You can specify a min and max value to get a random array index within the bound.

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Also, in your case it is possible that the do while loop will run forever as the exit condition in while loop might not happen for the same reason I described above.

Simplest change you can make is

randomColor = availColors[Math.floor(Math.random()*(availColors.length-1))];

Upvotes: 0

Kevin
Kevin

Reputation: 2802

I would remove the do while loop, as mentioned in the comments.

Here is your updated fiddle with one way to do this

var defaultColors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'],
    availColors = [],
    randomColor = '';

$('h3 span').each(function() 
{
        if(availColors.length == 0)
            availColors = defaultColors.slice(0);

        randomColor = availColors[Math.floor(Math.random() * availColors.length)];
        availColors = $.grep(availColors, function(value) 
                        {
                              return value != randomColor;
                        });
        $(this).css('color', randomColor);
});

Upvotes: 1

Related Questions