by LGforum October 7th 2012, 5:57 pm
No your right. I'm going blind.
For some reason I didn't see the rounding in your code...
But my question would be, why use the slow ':eq()' selector. The '.eq()' method will be quicker, like what you had at first... but even quicker than that would just be accessing the element by index.
- Code:
$(function() {
var whichToShow = Math.floor(Math.random() * $('.quote').length);
var div = $('.quote')[whichToShow];
if(div) $(div).fadeIn(1000);
});
Notice accessing it through index in the third line. No slow selectors and no extra function call. I added the IF, because your using the length property to limit the random number, which potentially could return a value out of range since the max is inclusive.
For example, you have 2 DIVs; div[0] and div[1]. A random number between 0 & 2 (inclusive) could return 2. div[2] does not exist and you'll hit an error.
Alternatively, you could change it to: Math.floor(Math.random() * $('.quote').length - 1);
Taking 1 off of the length will mean you don't have to perform that IF. As it will mean a random number between 0 & 1. Both div[0] and div[1] exist.
And even further improvement would be not using the same selector twice...
- Code:
$(function() {
var quotes = $('.quote');
var index = Math.floor(Math.random() * quotes.length - 1);
$(quotes[index]).fadeIn(1000);
});
Notice how your no longer parsing and performing the selector '.quote' twice anymore. Just the once and storing it in a variable.
Just some food for thought