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

              
                <section class="bcls-section">
<h2 id="inputs">Geographical Analytics Report</h2>

<fieldset class="bcls-fieldset"><legend>Basic Information</legend>

<p>By default, you will get results from the Brightcove Training Videos account.</p>

<p><span class="bcls-button" id="useMyAccount">Use My Account Instead</span></p>

<div id="basicInfo" style="display:none">
<table class="bcls-table">
	<tbody class="bcls-table__body">
		<tr>
			<td>Video Cloud Account (Publisher ID):</td>
			<td><input id="accountID" class="required aapi-request" type="text" size="55" /></td>
		</tr>
		<tr>
			<td class="align-top no-wrap">Client id:</td>
			<td><input id="client_id" class="required aapi-request" type="text" size="100" value="" />
			<p>&nbsp;</p>
			</td>
		</tr>
		<tr>
			<td class="align-top no-wrap">Client secret:</td>
			<td><input id="client_secret" class="required aapi-request" type="text" size="100" value="" />
			<p>&nbsp;</p>
			</td>
		</tr>
	</tbody>
</table>

<p class="small" id="n1"><sup class="red">[1]</sup> See <a href="/node/14056">Managing API Credentials</a> for information on getting client credentials.</p>
</div>
</fieldset>

<fieldset class="bcls-fieldset"><legend>Report Options</legend>

<h4>Date Range</h4>

<p>Start: <input id="fromDatePicker" size="30" placeholder="2016-01-01" /> (default: 30 days ago)</p>

<p>End: &nbsp;<input id="toDatePicker" size="30" placeholder="2016-01-31" /> (default: today)</p>

<p><span class="bcls-button" id="getData">Get Data for the Account</span></p>

<h3>Video Options</h3>

<p>To get results for a specific video, make a selection below</p>

<p><select id="videoSelector"></select></p>

<p class="text-warning" id="gettingDataDisplay">&nbsp;</p>
</fieldset>
</section>

<section class="bcls-section">
<h2 id="aapiRequest">Analytics API Request</h2>
<textarea id="requestURL" rows="3" cols="200">API request will appear here...</textarea></section>

<section class="bcls-section" id="results">
<h2>Geo Analytics Report</h2>

<div id="video_info">&nbsp;</div>

<table class="bcls-table">
	<thead class="bcls-table__head">
		<tr>
			<th>Country</th>
			<th>Video Views</th>
			<th>Average Viewed Seconds</th>
		</tr>
	</thead>
	<tbody id="reportTableBody">
	</tbody>
</table>
</section>

              
            
!

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
 */
.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: .5em;
  background-color: #333;
  border: 1px yellow solid;
  border-radius: .5em;
  color: yellow;
  cursor: pointer;
}
fieldset {
  color: #64AAB2;
  border: 1px #64AAB2 solid;
  border-radius: .5em;
}

.bcls-table {
  border-collapse: collapse;
}
code {
  color: #E4B842;
  font-family: 'Source Code Pro',monospace;
}
              
            
!

JS

              
                var BCLS = (function(window, document, Pikaday) {
  'use strict';
  var proxyURL = 'https://solutions.brightcove.com/bcls/bcls-proxy/bcls-proxy-v2.php',
    useMyAccount = document.getElementById('useMyAccount'),
    basicInfo = document.getElementById('basicInfo'),
    $accountID = document.getElementById('accountID'),
    account_id = '1752604059001',
    $client_id = document.getElementById('client_id'),
    $client_secret = document.getElementById('client_secret'),
    client_id = '',
    client_secret = '',
    $videoSelector = document.getElementById('videoSelector'),
    $reportTableBody = document.getElementById('reportTableBody'),
    fromDatePicker = document.getElementById('fromDatePicker'),
    toDatePicker = document.getElementById('toDatePicker'),
    getData = document.getElementById('getData'),
    $gettingDataDisplay = document.getElementById('gettingDataDisplay'),
    video_info = document.getElementById('video_info'),
    $requestURL = document.getElementById('requestURL'),
    currentVideo,
    currentVideoObj,
    analyticsData = {},
    chartData = [],
    callType,
    fromPicker,
    toPicker,
    now = new Date(),
    nowMS = now.valueOf(),
    then = new Date(nowMS - (1000 * 60 * 60 * 24 * 30)), // 30 days ago in milliseconds
    nowISO = now.toISOString().substr(0, 10), // get the date part of the date-time string
    thenISO = then.toISOString().substr(0, 10); // get the date part of the date-time string

  // more robust test for strings 'not defined'
  /**
   * tests for all the ways a variable might be undefined or not have a value
   * @param {*} x the variable to test
   * @return {Boolean} true if variable is defined and has a value
   */
  function isDefined(x) {
    if (x === '' || x === null || x === undefined) {
      return false;
    }
    return true;
  }

  /**
   * get selected value for single select element
   * @param {htmlElement} e the select element
   * @return {Object} object containing the `value` and selected `index`, and the option text
   */
  function getSelectedValue(e) {
    var val = e.options[e.selectedIndex].value,
      txt = e.options[e.selectedIndex].textContent,
      idx = e.selectedIndex;
    return {
      value: val,
      text: txt,
      index: idx
    };
  }

  /**
   * builds the data display
   * @param {Object[]} array of analytics items
   */
  function displayData(items) {
    var newTr,
      newTd,
      txt,
      results = new DocumentFragment();
    // display the video info
    video_info.textContent = 'Video: ' + currentVideoObj.text + ' (' + currentVideoObj.value + ')';
    items.forEach(function(item, index, items) {
      newTr = document.createElement('tr');
      newTd = document.createElement('td');
      txt = document.createTextNode(item.country_name);
      newTd.appendChild(txt);
      newTr.appendChild(newTd);
      newTd = document.createElement('td');
      txt = document.createTextNode(item.video_view);
      newTd.appendChild(txt);
      newTr.appendChild(newTd);
      newTd = document.createElement('td');
      txt = document.createTextNode(item.video_seconds_viewed);
      newTd.appendChild(txt);
      newTr.appendChild(newTd);
      results.appendChild(newTr);
    });
    $reportTableBody.appendChild(results);
  }

  /**
   * Builds the API requests and handles responses
   * @param {String} type the request type (getCount | getVideos | getAnalytics)
   */
  function buildRequest(type) {
    var options = {},
      parsedData,
      tmpArray,
      newVideoItem = {},
      videoItem,
      newEl,
      txt,
      i,
      iMax,
      item,
      fields,
      frag = new DocumentFragment();
    // add credentials if submitted
    if (isDefined(client_id) && isDefined(client_secret)) {
      options.client_id = client_id;
      options.client_secret = client_secret;
    }
    options.account_id = account_id;
    options.proxyURL = proxyURL;
    switch (type) {
      case 'getVideos':
        options.url = 'https://analytics.api.brightcove.com/v1/data?accounts=' + account_id + '&dimensions=video&limit=all&fields=video,video.name&sort=-video_view&from=' + fromDatePicker.value + '&to=' + toDatePicker.value;
        $requestURL.textContent = options.url;
        makeRequest(options, function(response) {
          parsedData = JSON.parse(response);
          // create the video selector items from the response items
          newEl = document.createElement('option');
          newEl.setAttribute('value', '');
          txt = document.createTextNode('Select a video');
          newEl.appendChild(txt);
          frag.appendChild(newEl);
          iMax = parsedData.items.length;
          for (i = 0; i < iMax; i++) {
            item = parsedData.items[i];
            newEl = document.createElement('option');
            newEl.setAttribute('value', item.video);
            txt = document.createTextNode(item['video.name']);
            newEl.appendChild(txt);
            frag.appendChild(newEl);
          }
          // append the options to the video selector
          $videoSelector.appendChild(frag);
        });
        break;
      case 'getAnalytics':
        currentVideo = currentVideoObj.value;
        // fields to return
        fields = 'country,country_name,video_view,video_seconds_viewed';
        options.url = 'https://analytics.api.brightcove.com/v1/data?accounts=' + account_id + '&dimensions=country&limit=all&fields=' + fields + '&from=' + fromDatePicker.value + '&to=' + toDatePicker.value + '&where=video==' + currentVideo;
        $requestURL.textContent = options.url;
        makeRequest(options, function(response) {
          parsedData = JSON.parse(response);
          // display the data
          displayData(parsedData.items);
        });
        break;
    }
  }

  /**
   * 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));
  }

  // add date pickers to the date input fields
  fromPicker = new Pikaday({
    field: fromDatePicker,
    format: 'YYYY-MM-DD'
  });
  toPicker = new Pikaday({
    field: toDatePicker,
    format: 'YYYY-MM-DD'
  });
  // set initial from/to values
  fromDatePicker.value = thenISO;
  toDatePicker.value = nowISO;

  // set event listeners
  useMyAccount.addEventListener('click', function() {
    if (basicInfo.getAttribute('style') === 'display:none') {
      basicInfo.setAttribute('style', 'display:block');
      useMyAccount.textContent = 'Use Sample Account';
    } else {
      basicInfo.setAttribute('style', 'display:none');
      useMyAccount.textContent = 'Use My Account Instead';
    }

  });
  $videoSelector.addEventListener('change', function() {
    // get video and geo selections
    currentVideoObj = getSelectedValue($videoSelector);
    buildRequest('getAnalytics');
  });
  getData.addEventListener('click', function() {
    account_id = (isDefined($accountID.value)) ? $accountID.value : account_id;
    $gettingDataDisplay.textContent = 'Getting video data...';
    buildRequest('getVideos');
  });

  return {};
})(window, document, Pikaday);

              
            
!
999px

Console