Tema: Css Random
Ver Mensaje Individual
  #9 (permalink)  
Antiguo 26/10/2010, 15:40
Avatar de stock
stock
 
Fecha de Ingreso: junio-2004
Ubicación: Monterrey NL
Mensajes: 2.390
Antigüedad: 19 años, 10 meses
Puntos: 53
Respuesta: Css Random

@masterojitos, quizás es "más simple" lo que propones pero varias cosas que deberíamos tomar en cuenta cuando programamos JavaScript ;)

* Separar el JavaScript del HTML
* Evitar usar el Global Scope
* Empaquetar el código
* Usar listeners adecuadamente
* etc...

Yo refactorizaría tu código de la siguiente manera:

Código Javascript:
Ver original
  1. var App = {
  2.    rand : function(min, max){
  3.       var argc = arguments.length;
  4.       if(argc == 0){
  5.          min = 0;
  6.          max = 2147483647;
  7.       }else if(argc == 1){
  8.          throw "Warning: rand() expects exactly 2 parameters, 1 given";
  9.       }
  10.       return Math.floor((Math.random() * (max - min + 1)) + min);
  11.    },
  12.  
  13.    change : function(id){
  14.       var aleatorio = this.rand(1, 30),
  15.          a = document.getElementById(id);
  16.  
  17.          a.rel = '../css/backgrounds/' + aleatorio + '.css';
  18.          a.innerHTML = aleatorio;
  19.    },
  20.  
  21.    on   : function(elem,type,cb,scope){
  22.         if(!elem){throw "El elemento es obligatorio!";}
  23.         scope = scope || elem;
  24.         cb = cb || function(){};
  25.        
  26.         if (document.addEventListener){
  27.             elem.addEventListener(type, function(event){
  28.                 cb.call(scope,elem,event);
  29.             },false);
  30.    
  31.         }else if(document.attachEvent){
  32.             elem.attachEvent( 'on' + type, function() {
  33.                 cb.call(scope,elem, window.event);
  34.             });
  35.         }
  36.    }
  37. }
  38.  
  39.  
  40.  
  41. App.on(window, "load", function(){
  42.  
  43.    var link = document.getElementById("back_change");
  44.  
  45.    App.on(link,"click",function(){
  46.  
  47.         App.change("back_change");
  48.  
  49.     });
  50.  
  51.    App.on();
  52.  
  53. });


Buen día :)

Última edición por stock; 26/10/2010 a las 15:50