JS Examples

by David Kyle

HTML

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css">
<div class="container">
  <div class="row">
    <div class="col">
      <h1 class="h1 header-label">
        JS Examples
      </h1>
    </div>
  </div>
  <div class="row">
    <div class="col">
      <input type="button" class="btn btn-primary" id="colorChangeButton" value="Randomize" />
    </div>
  </div>
</div>

JavaScript

'use strict';

let Application = (function(jQuery) { // Module declaration (with argument)
  let local = { // JS Object definition
    colors: [
      'Red',
      'Green',
      'Orange',
      'Blue',
      'Black',
      'Grey',
      'Purple',
      'Brown'
    ],
    $dom: null,
    events: {}
  };

  local.events.colorChangeClick = function(e) {
    randomizeHeaderColor();
  };

  /**
  Randomizes the header color
  */
  let randomizeHeaderColor = function() {
    let rnd = Math.floor(Math.random() * local.colors.length - 1);
    local.$dom.find('.header-label').css('color', local.colors[rnd]);
  };

  let init = function(args) {
    if (args) {
      if (args.root) {
        local.$dom = args.root;
      }
    } else {
      throw new Error('No arguments provided for module initialization.');
    }

    if (local.$dom) {
      jQuery()(function() {
        local.$dom.on('click', '#colorChangeButton', local.events.colorChangeClick);
      });
    } else {
      throw new Error('No DOM provided.');
    }
  };

  return { // Return statement that defines what is "exposed" from the module closure
    Randomize: randomizeHeaderColor,
    Init: init
  };
})(function() {
  return $;
}); // Invoking the module (and passing in the argument)

Application.Init({
  root: $(document)
});