Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Using last_viewed Data</h1>
<p>If you do not provide account information, a Brightcove Learning test account will be used.</p>
<div class="buttonBlock">
  <p><strong>Account Information</strong></p>
  <p><input id="account_id_input" type="text" size="30" value=""> Account id</p>
  <p><input id="client_id_input" type="text" size="30" value=""> Client id</p>
  <p><input id="client_secret_input" type="text" size="30" value=""> Client secret</p>
</div>
<div class="buttonBlock">
  <p><button id="get_last_viewed" class="bcls-button">Get last_viewed Information</button></p>
  <p><button id="reset_app" class="bcls-reset">Reset</button></p>
</div>
<p><strong>API request:</strong></p>
<textarea id="apiRequest" class="bcls-code" style="height:.7rem;min-height:.7rem;"></textarea>
<p><strong>Request method:</strong></p>
<textarea id="apiMethod" class="bcls-code" style="height:.7rem;min-height:.7rem;"></textarea>
<p><strong>Table of last_viewed player data:</strong></p>
<div id="playerTable" class="bcls-code"></div>
<p><strong>Raw player response data</strong></p>
<textarea id="apiResponse" class="bcls-code"></textarea>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
              
            
!

CSS

              
                /* * The body style is just for the
 * background color of the codepen.
 * Do not include in your code.
 */
body {
  background-color: #111;
  color: #f5f5f5;
  font-family: sans-serif;
  margin: 2em;
}
/*
 * Styles essential to the sample
 * are below
 */
body {
  background-color: #111;
  color: #f5f5f5;
  font-family: sans-serif;
  margin: 2em;
}
.bcls-code {
  color: #111;
  font-family: "Source Code Pro", monospace;
  padding: 1em;
  width: 90%;
  min-height: 5em;
  background-color: #cfcfcf;
  font-size: 1rem;
}
.bcls-button {
  padding: 0.5em;
  background-color: #333;
  border: 1px yellow solid;
  border-radius: 0.5em;
  color: yellow;
  cursor: pointer;
}
fieldset {
  color: #64aab2;
  border: 1px #64aab2 solid;
  border-radius: 0.5em;
}
.buttonBlock {
  display: inline-block;
  padding: 1em;
  border-right: 1px white solid;
  vertical-align: top;
}

.bcls-Data-Table {
  border: 1px RGB(54, 72, 133) solid;
  border-collapse: collapse;
}

.bcls-Data-Table td, .bcls-Data-Table th {
  padding: .5em;
  border: 1px RGB(54, 72, 133) solid;
  border-collapse: collapse;
}

              
            
!

JS

              
                var BCLS = (function(window, document) {
  var playerMngmtURL = "https://players.api.brightcove.com/v2/accounts/",
    proxyURL =
      "https://solutions.brightcove.com/bcls/bcls-proxy/bcls-proxy-v2.php",
    default_account_id = "57838016001",
    all_player_data = "";
  (account_id_input = document.getElementById("account_id_input")),
    (client_id_input = document.getElementById("client_id_input")),
    (client_secret_input = document.getElementById("client_secret_input")),
    (apiRequest = document.getElementById("apiRequest")),
    (playerTable = document.getElementById("playerTable")),
    (apiMethod = document.getElementById("apiMethod")),
    (apiResponse = document.getElementById("apiResponse")),
    // buttons
    (all_buttons = document.querySelectorAll(".bcls-button")),
    (get_last_viewed = document.getElementById("get_last_viewed")),
    (reset_app = document.getElementById("reset_app"));

  /**
   * event listeners
   */
  get_last_viewed.addEventListener("click", function() {
    createRequest("get_last_viewed");
  });

  reset_app.addEventListener("click", function() {
    reset();
  });

  /**
   * disables all buttons so user can't submit new request until current one finishes
   */
  function disableButtons() {
    var i,
      iMax = all_buttons.length;
    for (i = 0; i < iMax; i++) {
      all_buttons[i].setAttribute("disabled", "disabled");
      all_buttons[i].setAttribute(
        "style",
        "color:#999;cursor:not-allowed;border:1px #999 solid;"
      );
    }
  }

  /**
   * enables a button element
   * @param {htmlElement} button the button
   */
  function enableButton(button) {
    button.removeAttribute("disabled");
    button.removeAttribute("style");
  }

  function reset() {
    disableButtons();
    enableButton(get_last_viewed);
  }

  /**
   * sets up the data for the API request
   * @param {String} id the id of the button that was clicked
   */
  function createRequest(id) {
    var endPoint = "",
      options = {},
      requestBody = {};
    // disable buttons to prevent a new request before current one finishes
    disableButtons();
    options.account_id =
      account_id_input.value.length > 0
        ? account_id_input.value
        : "57838016001";
    if (
      client_id_input.value.length > 0 &&
      client_secret_input.value.length > 0
    ) {
      options.client_id = client_id_input.value;
      options.client_secret = client_secret_input.value;
    }
    options.proxyURL = proxyURL;
    endPoint = options.account_id + "/players";
    options.url = playerMngmtURL + endPoint;
    options.requestType = "GET";
    apiRequest.textContent = options.url;
    apiMethod.textContent = options.requestType;
    makeRequest(options, function(response) {
      var parsedData,
        i,
        iMax,
        option,
        frag = document.createDocumentFragment();
      parsedData = JSON.parse(response);
      apiResponse.textContent = JSON.stringify(parsedData, null, 2);
      apiResponse.textContent = JSON.stringify(parsedData, null, "  ");
      // enable the create experience button
      disableButtons();
      // Using returned data, call function that builds the table
      buildTable(parsedData);
    });
  }

  /**
   * send API request to the proxy
   * @param  {Object} options for the request
   * @param  {String} options.url the full API request URL
   * @param  {String="GET","POST","PATCH","PUT","DELETE"} requestData [options.requestType="GET"] HTTP type for the request
   * @param  {String} options.proxyURL proxyURL to send the request to
   * @param  {String} options.client_id client id for the account (default is in the proxy)
   * @param  {String} options.client_secret client secret for the account (default is in the proxy)
   * @param  {JSON} [options.requestBody] Data to be sent in the request body in the form of a JSON string
   * @param  {Function} [callback] callback function that will process the response
   */
  function makeRequest(options, callback) {
    var httpRequest = new XMLHttpRequest(),
      response,
      proxyURL = options.proxyURL,
      // response handler
      getResponse = function() {
        try {
          if (httpRequest.readyState === 4) {
            if (httpRequest.status >= 200 && httpRequest.status < 300) {
              response = httpRequest.responseText;
              // some API requests return '{null}' for empty responses - breaks JSON.parse
              if (response === "{null}") {
                response = null;
              }
              // return the response
              callback(response);
            } else {
              alert(
                "There was a problem with the request. Request returned " +
                  httpRequest.status
              );
            }
          }
        } catch (e) {
          alert("Caught Exception: " + e);
        }
      };
    /**
     * set up request data
     * the proxy used here takes the following request body:
     * JSON.stringify(options)
     */
    // set response handler
    httpRequest.onreadystatechange = getResponse;
    // open the request
    httpRequest.open("POST", proxyURL);
    // set headers if there is a set header line, remove it
    // open and send request
    httpRequest.send(JSON.stringify(options));
  }

  /**
   * sort an array of objects based on an object property
   * @param {array} targetArray - array to be sorted
   * @param {string|number} objProperty - object property to sort on
   * @return sorted array
   */
  function sortArray(targetArray, objProperty) {
    targetArray.sort(function(a, b) {
      var propA = a[objProperty].length,
        propB = b[objProperty].length;
      // sort ascending; reverse propA and propB to sort descending
      if (propB < propA) {
        return -1;
      } else {
        return 1;
      }
    });
    return targetArray;
  }

  /**
   *builds a table from the players' last_viewed array
   * @param JSON rawPlayerData - all data returned from the Player Mgmt API call /players
   */

  function buildTable(rawPlayerData) {
    // Build skeleton of table
    playerTable.innerHTML =
      '<table id="myTable"><tr><th style="width: 40%">Name</th><th style="width: 20%">Player ID</th><th style="width: 40%">last_viewed Info</th></tr></table>';

    // Extract items array from raw JSON
    var arrayOfPlayers = rawPlayerData.items;
    // Sort so players with views at the top of table
    sortArray(arrayOfPlayers, "last_viewed");
    // Get number of players
    numPlayers = arrayOfPlayers.length;
    // Get table element for later use
    var table = document.getElementById("myTable");
    // Style table
    table.setAttribute("class", "bcls-Data-Table");

    //Loop over all players
    for (var i = 0; i < numPlayers; i++) {
      var lastViewedAra = arrayOfPlayers[i].last_viewed;
      var lastViewedLength = lastViewedAra.length;

      // Insert a row
      var row = table.insertRow(i + 1);

      // Insert new cells (<td> elements):
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      var cell3 = row.insertCell(2);

      // Add some text to the new cells:
      cell1.innerHTML = rawPlayerData.items[i].name;
      cell2.innerHTML = rawPlayerData.items[i].id;
      // If last_viewed array has entries, display them, otherwise display Not viewed
      if (lastViewedLength > 0) {
        //Dynamically build one or more <ul> elements
        var myUL = "<ul>",
          formattedDate;
        // Loop over all elements in single player's last_viewed array
        for (var j = 0; j < lastViewedLength; j++) {
          formattedDate = lastViewedAra[j].date;
          formattedDate = moment(formattedDate).format("DD MMM YY");
          var myLI =
            "<li> Count: " +
            lastViewedAra[j].count +
            " Date: " +
            formattedDate +
            "</li>";
          myUL += myLI;
        }
        myUL += "</ul>";
        cell3.innerHTML = myUL;
      } else {
        cell3.innerHTML = "Not viewed";
      }
    }
  }

  // set initial state
  reset();
})(window, document);

              
            
!
999px

Console