function - Refactoring in Javascript -


here code:

var randomcolor = ["red", "blue", "green", "#9cba7f", "yellow", "#bf5fff"];  function setrandomcolor() {  return randomcolor[math.floor(math.random() * randomcolor.length)]; }  $('.mastermind_master_cpu').each(function() {  $(this).find('td').each(function() {    $(this).css("background-color", setrandomcolor);  }) }) 

as can see, mastermind_master_cpu table randomly fill different background color. problem have ten different tables , repeating every time. know how can go making 1 function / variable , calling when needed?

thanks!

create class, random_color, apply each table in addition current class, this:

<table class="mastermind_master_cpu random_color">...</table> 

then can use once:

$('.random_color').each(function() {  $(this).find('td').each(function() {    $(this).css("background-color", setrandomcolor);  }) }) 

but cookie monster points out, can done more succinctly:

$('.random_color td').css("background-color", setrandomcolor); 

demonstration


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -