jQuery addClass example

Change class name on click in jQuery

by Sascha

HTML

<div id="banner-message">
  <p>Hello World</p>
  <button>Change color</button>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

JavaScript

function combineArrays(array_of_arrays, array_prefixes) {

  // First, handle some degenerate cases...

  if (!array_of_arrays) {
    // Or maybe we should toss an exception...?
    return [];
  }

  if (!Array.isArray(array_of_arrays)) {
    // Or maybe we should toss an exception...?
    return [];
  }

  if (array_of_arrays.length == 0) {
    return [];
  }

  for (let i = 0; i < array_of_arrays.length; i++) {
    if (!Array.isArray(array_of_arrays[i]) || array_of_arrays[i].length == 0) {
      // If any of the arrays in array_of_arrays are not arrays or zero-length, return an empty array...
      return [];
    }
  }

  // Done with degenerate cases...

  // Start "odometer" with a 0 for each array in array_of_arrays.
  let odometer = new Array(array_of_arrays.length);
  odometer.fill(0);

  let output = [];

  let newCombination = formCombination(odometer, array_of_arrays, array_prefixes);

  output.push(newCombination);

  while (odometer_increment(odometer, array_of_arrays)) {
    newCombination = formCombination(odometer, array_of_arrays, array_prefixes);
    output.push(newCombination);
  }

  return output;
} /* combineArrays() */


// Translate "odometer" to combinations from array_of_arrays
function formCombination(odometer, array_of_arrays, array_prefixes) {
  // In Imperative Programmingese (i.e., English):
  // let s_output = "";
  // for( let i=0; i < odometer.length; i++ ){
  //    s_output += "" + array_of_arrays[i][odometer[i]]; 
  // }
  // return s_output;

  // In Functional Programmingese (Henny Youngman one-liner):
  return odometer.reduce(
    function(accumulator, odometer_value, odometer_index) {
      return accumulator + " " + array_prefixes[odometer_index] + ":" + array_of_arrays[odometer_index][odometer_value];
    },
    ""
  );
} /* formCombination() */

function odometer_increment(odometer, array_of_arrays) {

  // Basically, work you way from the rightmost digit of the "odometer"...
  // if you're able to increment without...