Create a random combination with CSS classes using javascript or jquery

1

Hello guys, I was wondering if anyone knows any solution how to do a combination of css classes using javascript or jquery?

What I would like is to have links and each of these links have several classes of color, and after selecting one of the links, generate a page with a bg of one color and that the font is of another, which is always random for each person to click, as this will be used as a theme for managed sites that I'm putting together.

    
asked by anonymous 07.07.2015 / 15:30

1 answer

3

You can sort the classes in an array. Or rather, two, one for the BG and another for the source, so you guarantee some contrast. Example:

var classesBg = ['fundoAzul', 'fundoVermelho', 'fundoVerde'];
var classesTexto = ['textoBranco', 'textoPreto', 'textoCinza'];
function sorteia(arr) {
    var rand = Math.floor(Math.random() * arr.length);
    return arr[rand];
}

document.getElementById('troca').addEventListener('click', function() {
    var classeBg = sorteia(classesBg);
    var classeTexto = sorteia(classesTexto);
    var elemento = document.getElementById('conteudo');
    elemento.className = classeBg + ' ' + classeTexto;
}); 
.fundoAzul {
  background-color: #0000ff;
}
.fundoVermelho {
  background-color: #ff0000;
}
.fundoVerde {
  background-color: #00ff00;
}
.textoBranco {
  color: #ffffff;
}
.textoPreto {
  color: #000000;
}
.textoCinza {
  color: #aaaaaa;
}
<p id="conteudo">Texto texto texto</p>
<button type="button" id="troca">trocar</button>
    
07.07.2015 / 15:41