2

I have a list of colors, that needs to be animated as a document body background-color.

var bgs = [
    "BlanchedAlmond",
    "Blue",
    "BlueViolet",
    "Brown",
    "BurlyWood",
    "CadetBlue",
    "Chartreuse",
    "Chocolate",
    "Coral",
    "CornflowerBlue",
    "Cornsilk",
    "Crimson",
    "Cyan",
    "DarkBlue",
    "DarkCyan"
];

Now, using colorToHex() custom function for mootools, I ended up with the following code:

window.addEvent('domready', function() {
  var current;
  (function() {
    selected = ~~(Math.random() * bgs.length);

    // is it a right way to avoid the repetition?
    current = (selected == current) ? ((bgs.length-1) % (selected+1)) : selected;
    // -1 is to avoid the edge case,
    // +1 is to avoid the NaN in case select is 0

    $(document.body).set('tween', {duration: '1500'})
      .tween("background-color",bgs[current].colorToHex());
  }).periodical(1000);
});

Questions

  1. (optimization of the aforementioned chunks of code) From the performance optimization perspective, is there a better way to perform this animation?

  2. (vs. jQuery) Would the jQuery counterpart be more efficient and elegant?

Community
  • 1
  • 1
vulcan raven
  • 32,612
  • 11
  • 57
  • 93

2 Answers2

3

Ok, I had 2 minutes to check it and try to make it better :)

..here is the working example : http://jsbin.com/evofuw/2 (and the code here http://jsbin.com/evofuw/2/edit#javascript)

..btw, I found some problems in your version:

  • selected = ~~(Math.random() * bgs.length); you haven't defined selected, + there is a built in getRandom() method available for Arrays in MooTools.

  • to avoid repetition and all that 'mess' you did, delete that random element from that array ;)

  • Why you're not using the onComplete tween callback? Using periodical (setInterval) is never the same as using callbacks (and most of the times is not correct).

  • Each time you're running that anonym function you're retrieving (by $) the body that is not cached. Ok, it's the body but it's a good habit to cache elements :)

  • About q#2, definitely not. :)


Here is my version:

// a namespace, more elegant :)
var app = {};

// the array with colors
app.bgs = [
    "BlanchedAlmond",
    "Blue",
    "BlueViolet",
    "Brown",
    "BurlyWood",
    "CadetBlue",
    "Chartreuse",
    "Chocolate",
    "Coral",
    "CornflowerBlue",
    "Cornsilk",
    "Crimson",
    "Cyan",
    "DarkBlue",
    "DarkCyan"
];

// the function to change bg color
app.changeBGColor = function( b ){
  // random select element
  var selected = app.bgs.getRandom();
  // delete that element from the array
  app.bgs.erase(selected);
  // tween background color
  b.tween('background-color',selected.colorToHex());
}

window.addEvent('domready', function() {
  // cache body element
  var b = $(document.body);

  // set tween stuff
  b.set('tween', {
    duration : 1500,
    onComplete : function(){
      if( app.bgs.length ) { // if the array contains elements, change color
        app.changeBGColor(b);
      } else { // otherwise do nothing
        console.log('array empty! end!');
      }
    }
  });

  // start 1st time
  app.changeBGColor(b);

});

ps. if you want to animate 'forever', just use another array (where to push the deleted values) and then swap array when the other one is empty

stecb
  • 14,478
  • 2
  • 50
  • 68
0

Answer 1:

I agree with stecb; You can cache the values and make use of getRandom(). But in order to continue the animation indefinitely, you don't want to delete the element from array. Therefore, to avoid the duplicate selection consecutively, you just need to switch the places of (cached_length-1) and (selected+1).

Also, the method colorToHex suggested by csuwldcat (the one you cited) is most costly in the entire animation in terms of performance. I would highly suggest you use Hex code in the bgs array. If that is not an option, the you must use colourNameToHex() function by Greg on the same page.

Finally periodical( _interval ) is for setting the delay between the adjacent tween ops whereas duration is the time taken by one color transition. Mootools also provides a delay() function to pause the sequential flow. But in this case, use of priodical() to fire the transition after fixed interval makes sense.

Here is another version of your code:

window.addEvent('domready', function() {
    var cached_length = bgs.length;
    var myElement = new Fx.Tween(document.body, {duration: '1500'});
    var current, selected;
    (function() {
       selected = ~~(Math.random() * bgs.length);
       current = (selected == current) ?
                         ((selected + 1) % (cached_length - 1)) : selected;

       /* console.info("current: "+bgs[current]); */
       myElement.start("background-color",bgs[current]); // if you use Hex codes 
                                                        // instead of color names
    }).periodical(1000);
});

Answer 2:

Since jQuery would require a plugin jQuery.Color to animate the background-color, that kind of an extra layered complexity may effect the performance, but it cannot compete the performance of Mootools (which is an extended Javascript core as opposed to a layered framework).

Community
  • 1
  • 1
vulcan raven
  • 32,612
  • 11
  • 57
  • 93