HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<h2>Video Report by Player and Day</h2>
<fieldset class="bcls-fieldset"><legend>Basic Information</legend>
<p>By default, you will get results from the Brightcove Training Videos account.</p>
<p><button class="bcls-button" id="useMyAccount">Use My Account Instead</button></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 style="vertical-align:top;white-space:nowrap;">Client id:</td>
<td><input id="clientID" class="required aapi-request" type="text" size="100" value="" />
<p> </p>
</td>
</tr>
<tr>
<td style="vertical-align:top;white-space:nowrap;">Client secret:</td>
<td><input id="clientSecret" class="required aapi-request" type="text" size="100" value="" /></td>
</tr>
</tbody>
</table>
<p style="font-size:small;" id="n1"><sup>[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>Date Range for Report</legend>
<p>Start: <input id="fromDatePicker" size="30" /></p>
<p>End: <input id="toDatePicker" size="30" /></p>
<p><button class="bcls-button" id="getData">Get Data</button></p>
<pre class="line-numbers">
<code class="language-json" id="requestDisplay">API request will appear here..</code></pre>
<p style="color:#990000;" id="gettingDataDisplay">Messages will appear here...</p>
</fieldset>
</section>
<section class="bcls-section">
<h2 id="results">Video Data</h2>
<p><select id="playerSelector"></select><select id="videoSelector" style="opacity:.3;"></select></p>
<table class="bcls-table">
<thead class="bcls-table__head">
<tr>
<th>Player</th>
<th>Video</th>
<th>Date</th>
<th>Plays</th>
<th>Avg viewed seconds</th>
<th>Total viewed seconds</th>
</tr>
</thead>
<tbody id="reportTableBody">
</tbody>
</table>
</section>
<section class="bcls-section">
<h2 id="csvData">CSV Data</h2>
<p>Below is the CSV data corresponding to the table above:</p>
<textarea name="csvDisplay" id="csvDisplay" style="width:100%;height:4em;"></textarea>
</section>
/* * 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;
}
code {
color: #E4B842;
font-family: 'Source Code Pro',monospace;
}
var BCLS = (function (window, document, datepickr) {
var callNumber = 0,
useMyAccount = document.getElementById("useMyAccount"),
basicInfo = document.getElementById("basicInfo"),
accountID = document.getElementById("accountID"),
clientID = document.getElementById("clientID"),
clientSecret = document.getElementById("clientSecret"),
dateSelector = document.getElementById("dateSelector"),
playerSelector = document.getElementById("playerSelector"),
videoSelector = document.getElementById("videoSelector"),
reportTableBody = document.getElementById("reportTableBody"),
csvDisplay = document.getElementById('csvDisplay'),
proxyURL = "https://solutions.brightcove.com/bcls/bcls-proxy/bcls-proxy-v2.php",
currentPlayerIndex = 0,
currentVideoIndex = 0,
currentDayIndex = 0,
currentPlayer,
currentPlayerName,
currentVideo,
currentVideoName,
currentDay,
playerMax,
videoMax,
dayMax,
daysArray = [],
dateToMS,
dateFromMS,
videoData,
playerData,
playersArray = [],
analyticsData = {},
playerID,
videoID,
dayMS,
fromDate = document.getElementById("fromDatePicker"),
toDate = document.getElementById("toDatePicker"),
getData = document.getElementById("getData"),
requestDisplay = document.getElementById('requestDisplay'),
gettingDataDisplay = document.getElementById("gettingDataDisplay"),
today = new Date(),
monthAgo = new Date(today - (30 * 24 * 60 * 60 * 1000)),
playerSelectTemplate = "{{#items}}<option value=\"{{player}}\">{{player_name}}</options>{{/items}}",
videoSelectTemplate = "{{#items}}<option value=\"{{video}}\">{{video_name}}</options>{{/items}}",
callType;
/**
* Logging function - safe for IE
* @param {string} context description of the data
* @param {*} message the data to be logged by the console
* @return {}
*/
function bclslog(context, message) {
if (window["console"] && console["log"]) {
console.log(context, message);
}
return;
}
// more robust test for strings "not defined"
function isDefined (v) {
if (v === "" || v === null || v === undefined || v === NaN) {
return false;
}
return true;
}
/**
* get the 3-letter name for a month
* @param {number} month 0-based number of the month
*/
function getMonthName(month) {
var name;
switch (parseInt(month)) {
case 0:
name = "Jan";
break;
case 1:
name = "Feb";
break;
case 2:
name = "Mar";
break;
case 3:
name = "Apr";
break;
case 4:
name = "May";
break;
case 5:
name = "Jun";
break;
case 6:
name = "Jul";
break;
case 7:
name = "Aug";
break;
case 8:
name = "Sep";
break;
case 9:
name = "Oct";
break;
case 10:
name = "Nov";
break;
case 11:
name = "Dec";
break;
}
return name;
}
function displayData() {
var displayStr, csvDisplayString = '', playerObject, videoObject, template, i, iMax, item;
currentPlayer = playerSelector.options[playerSelector.selectedIndex].value;
// bclslog('currentPlayer', currentPlayer);
currentVideoIndex = videoSelector.selectedIndex;
playerObject = analyticsData[currentPlayer];
// bclslog('analyticsData[currentPlayer]', analyticsData[currentPlayer]);
// bclslog('currentVideoIndex', currentVideoIndex);
// bclslog('playerObject.items[currentVideoIndex]', playerObject.items[currentVideoIndex]);
videoObject = playerObject.items[currentVideoIndex];
// bclslog('videoObject', videoObject);
displayStr = "<tr style=\"background-color:#64AAB2;color:#FFF;\"><th colspan=\"6\">" + playerObject.player_name + "</th></tr>";
cvsDisplayString = '"Video Name","","Total Plays","Total Average Seconds Viewed","Total Seconds Viewed" \n';
displayStr += '<tr><td></td><td>' + videoObject.video_name + '</td><td>Totals</td><td>' + videoObject.totalPlays + '</td><td>' + videoObject.totalAvgSecondsViewed + '</td><td>' + videoObject.totalSecondsViewed + '</td></tr>';
csvDisplayString += '"' + videoObject.video_name + '","Totals","' + videoObject.totalPlays + '","' + videoObject.totalAvgSecondsViewed + '","' + videoObject.totalSecondsViewed + '" \n' + '"Date","Views","Avg Viewed Seconds","Total Viewed Seconds" \n';
iMax = videoObject.items.length;
for (i = 0; i < iMax; i++) {
item = videoObject.items[i];
displayStr += '<tr><td colspan=\"2\"></td><td>' + item.date + '</td><td>' + item.video_view + '</td><td>' + item.avgSecondsViewed + '</td><td>' + item.totalSecondsViewed + '</td></tr>';
csvDisplayString += '"' + item.date + '","' + item.video_view + '","' + item.avgSecondsViewed + '","' + item.totalSecondsViewed + '" \n';
}
csvDisplay.value = csvDisplayString;
reportTableBody.innerHTML = displayStr;
}
function getTotals() {
var player, video, i, iMax, j, jMax, item, date, thisVideo;
for (player in analyticsData) {
jMax = analyticsData[player].items.length;
for (j = 0; j < jMax; j++) {
thisVideo = analyticsData[player].items[j];
iMax = thisVideo.items.length;
thisVideo.totalPlays = 0;
thisVideo.totalSecondsViewed = 0;
thisVideo.totalCompletedViews = 0;
for (i = 0; i < iMax; i++) {
item = thisVideo.items[i];
if (isDefined(item.date)) {
date = new Date(item.date);
item.date = dateToISO(date);
thisVideo.totalPlays += item.video_view;
thisVideo.totalSecondsViewed += item.totalSecondsViewed;
} else {
bclslog('item with no date', item);
}
}
if (thisVideo.totalPlays > 0) {
thisVideo.totalAvgSecondsViewed = thisVideo.totalSecondsViewed / thisVideo.totalPlays;
thisVideo.totalCompletedViews = thisVideo.totalCompletedViews / thisVideo.totalPlays;
} else {
thisVideo.totalAvgSecondsViewed = 0;
thisVideo.totalCompletedViews = 0;
}
gettingDataDisplay.textContent = 'Data processing complete';
}
}
}
function makeAnalyticsCall(callURL) {
var httpRequest = new XMLHttpRequest(),
options = {},
newItem = {},
data,
requestParams,
newEl,
txt,
getResponse = function () {
var i,
j,
k,
player,
video,
itemsmax,
analytics,
item,
newItem = {},
thisVideo;
try {
if (httpRequest.readyState === 4) {
if (httpRequest.status >= 200 && httpRequest.status < 300) {
data = JSON.parse(httpRequest.responseText);
bclslog('data', data);
} else {
alert('There was a problem with the request. Request returned ' + httpRequest.status);
}
}
} catch (e) {
bclslog('e', e);
}
if (isDefined(data)) {
switch (callType) {
case "players":
frag = new DocumentFragment();
callNumber++;
// save the data for getting the analytics
playerData = data;
newEl = document.createElement('option');
txt = document.createTextNode('Select a Player');
newEl.appendChild(txt);
frag.appendChild(newEl);
playerMax = playerData.items.length;
// add players to the analytics data object
for (i = 0; i < playerData.items.length; i++) {
playerData.items[i].player = (isDefined(playerData.items[i].player)) ? playerData.items[i].player : "noPlayerId";
if (playerData.items[i].player !== "noPlayerId") {
playersArray.push(playerData.items[i].player);
}
playerData.items[i].player_name = (isDefined(playerData.items[i].player_name)) ? playerData.items[i].player_name : "noPlayerName";
if (isDefined(playerData.items[i].player)) {
analyticsData[playerData.items[i].player] = {};
analyticsData[playerData.items[i].player].player_name = playerData.items[i].player_name;
analyticsData[playerData.items[i].player].items = [];
}
newEl = document.createElement('option');
txt = document.createTextNode(playerData.items[i].player_name);
newEl.appendChild(txt);
newEl.setAttribute('value', playerData.items[i].player);
frag.appendChild(newEl);
}
// populate the player selector
playerSelector.appendChild(frag);
playerSelector.options[0].setAttribute("selected", "selected");
getVideoData();
break;
case "videos":
frag = new DocumentFragment();
callNumber++;
// save the data for getting the analytics
videoData = data;
newEl = document.createElement('option');
txt = document.createTextNode('Select a Video');
newEl.appendChild(txt);
frag.appendChild(newEl);
// add videos to the analytics data object
videoMax = videoData.items.length;
for (player in analyticsData) {
for (j = 0; j < videoMax; j++) {
video = videoData.items[j];
video.video_name = (isDefined(video.video_name)) ? video.video_name : "unknown";
video.video = (isDefined(video.video)) ? video.video : "unknown";
analyticsData[player].items[j] = {};
analyticsData[player].items[j].id = video.video;
analyticsData[player].items[j].video_name = video.video_name;
analyticsData[player].items[j].items = [];
newEl = document.createElement('option');
txt = document.createTextNode(video.video_name);
newEl.appendChild(txt);
newEl.setAttribute('value', video.video);
frag.appendChild(newEl);
}
}
// populate the video selector
videoSelector.appendChild(frag);
videoSelector.options[0].setAttribute("selected", "selected");
getAnalyticsData();
break;
case "analytics":
callNumber++;
itemsmax = data.items.length;
// bclslog('data',data);
videoMax = analyticsData[currentPlayer].items.length;
for (k = 0; k < videoMax; k++) {
thisVideo = analyticsData[currentPlayer].items[k];
newItem = {};
newItem.video_view = 0;
newItem.avgSecondsViewed = 0;
newItem.totalSecondsViewed = 0;
newItem.date = currentDay.from;
for (i = 0; i < itemsmax; i++) {
if (data.items[i].video === thisVideo.id) {
item = data.items[i];
newItem.video_view = item.video_view;
newItem.avgSecondsViewed = item.video_seconds_viewed / item.video_view;
newItem.totalSecondsViewed = item.video_seconds_viewed;
}
}
analyticsData[currentPlayer].items[k].items.push(newItem);
}
if (currentDayIndex < dayMax - 1) {
currentDayIndex++;
getAnalyticsData();
} else if (currentPlayerIndex < playerMax - 1) {
currentDayIndex = 0;
currentVideoIndex = 0;
currentPlayerIndex++;
getAnalyticsData();
} else {
gettingDataDisplay.textContent = "Data retrieved - " + callNumber + " API calls made - processing data...";
// bclslog("analyticsData", analyticsData);
getTotals();
}
break;
}
}
};
if (isDefined(clientID.value)) {
options.client_id = clientID.value;
}
if (isDefined(clientSecret.value)) {
options.client_secret = clientSecret.value;
}
options.url = callURL;
options.requestMethod = "GET";
options.account_id = accountID.value;
options.requestData = null;
// set up request data
// set response handler
httpRequest.onreadystatechange = getResponse;
// open the request
httpRequest.open('POST', proxyURL);
// open and send request
httpRequest.send(JSON.stringify(options));
}
// get the analytics data for the videos
function getAnalyticsData() {
var callURL,
account_id = (isDefined(accountID.value)) ? accountID.value : "1752604059001";
gettingDataDisplay.innerHTML = "Getting analytics data - making request number " + callNumber;
callType = "analytics";
currentPlayer = playerData.items[currentPlayerIndex].player;
// currentVideo = videoData.items[currentVideoIndex].video;
currentDay = daysArray[currentDayIndex];
callURL = "https://analytics.api.brightcove.com/v1/data?accounts=" + account_id + "&dimensions=video&from=" + currentDay.from + "&to=" + currentDay.to + "&where=player==" + currentPlayer + "&fields=video_view,video_seconds_viewed,video";
requestDisplay.textContent = callURL;
makeAnalyticsCall(callURL);
}
// get the video analytics data
function getVideoData() {
var callURL = "";
account_id = (isDefined(accountID.value)) ? accountID.value : "1752604059001";
gettingDataDisplay.innerHTML = "Getting video data...";
callType = "videos";
callURL = "https://analytics.api.brightcove.com/v1/data?accounts=" + account_id + "&dimensions=video&limit=10&fields=video,video_name&sort=-video_view&from=" + dateFromMS + "&to=" + dateToMS;
requestDisplay.textContent = callURL;
makeAnalyticsCall(callURL);
}
// get all players for the selected time period
function getPlayersData() {
var callURL = "";
account_id = (isDefined(accountID.value)) ? accountID.value : "1752604059001";
gettingDataDisplay.innerHTML = "Getting player data...";
callType = "players";
callURL = "https://analytics.api.brightcove.com/v1/data?accounts=" + account_id + "&dimensions=player&limit=5&fields=player,player_name&sort=-video_view&from=" + dateFromMS + "&to=" + dateToMS;
requestDisplay.textContent = callURL;
makeAnalyticsCall(callURL);
}
// add date pickers to the date input fields
datepickr(fromDate, {
'dateFormat': 'Y-m-d'
});
datepickr(toDate, {
'dateFormat': 'Y-m-d'
});
/**
* return ISO 8601 date string (YYYY-MM-DD) for JS date
* @param {Date} date a Date object
* @return {String} the date in ISO format (date part only)
*/
function dateToISO(date) {
var y = date.getFullYear(),
m = date.getMonth(),
d = date.getDate(),
isoDate;
y = y.toString();
m = m + 1;
if (m < 10) {
m = "0" + m.toString();
} else {
m = m.toString();
}
if (d < 10) {
d = "0" + d.toString();
} else {
d = d.toString();
}
isoDate = y + "-" + m + "-" + d;
return isoDate;
}
// default date range values
toDate.value = dateToISO(today);
fromDate.value = dateToISO(monthAgo);
getData.addEventListener("click", function () {
var totalDays, i;
dateFromMS = new Date(fromDate.value).valueOf();
dateToMS = new Date(toDate.value).valueOf();
/**
* what follows is just math
* to create to and from params for API calls
* 86400000 = 1 day in milliseconds
*/
totalDays = Math.round((dateToMS - dateFromMS)/86400000);
for (i = 0; i < (totalDays - 1); i++) {
daysArray[i] = {from : dateFromMS + (i * 86400000), to : dateFromMS + ((i + 1) * 86400000) - 1};
}
dayMax = daysArray.length;
getPlayersData();
});
videoSelector.addEventListener("change", displayData);
playerSelector.addEventListener("change", function() {
videoSelector.setAttribute('style', '');
displayData();
});
useMyAccount.addEventListener("click", function () {
if (basicInfo.getAttribute('style') === "display:none;") {
basicInfo.setAttribute('style', 'display:block;');
useMyAccount.innerHTML = "Use Sample Account";
} else {
basicInfo.setAttribute('style', 'display:none;');
useMyAccount.innerHTML = "Use My Account Instead";
}
});
csvDisplay.addEventListener('click', function() {
this.select();
});
})(window, document, datepickr);
Also see: Tab Triggers