Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's 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 it's URL and the proper URL extention.

+ 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

Save Automatically?

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

              
                <div id="topStuff"></div>

<h1>Jedi Library</h1>

<p>Find Starwars info you will!</p>
<span id="topLevelPrompt">Start by looking in Library Archives at Starwars:</span> <select id="cboDataType" onchange="changeDataType(this)">
  <option value="planets" selected>Planets</option>
  <option value="people">People</option>
  <option value="films">Films</option>
  <option value="starships">Starships</option>
  <option value="vehicles">Vehicles</option>
  <option value="species">Species</option>
</select>
&nbsp;<br>&nbsp;<br>
<div id="info">...</div>
<div>
</div>
<br>
<!-- <button onclick="toggleEventLog()" id="btnEventLogToggle">View Event Log</button> -->
<div id="status">...</div>

<div id="atp">About this Pen</div>
<p>This is just an example of using the: <a href="https://swapi.co/" target="_blank">Star Wars API</a>.</p>


              
            
!

CSS

              
                @import url("https://fonts.googleapis.com/css?family=Montserrat:400,400i,700");

body {
  margin: 0;
  padding: 2rem;
  font-family: Montserrat, sans-serif;
  color: lightgreen;
  background:black;
  padding-top:0px;
  background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/1658514/jediLib1.png);
  background-repeat:no-repeat;
}

select {
  background:yellow;
  font-size:12.5pt;
  color:red;
}

#info {
  height:300px;
  width: 600px;
  bdackground:black;
  border:solid lightgreen 2px;
  border-radius:8px;
  padding:6px;
  overflow-x:hidden;
  overflow-y:auto;
  transform: perspective(800px) rotateX(25deg);
}

h1 {
  color:#21B3BD;
  margin-top:3px;
}

.lbl {
  background:orange;
  color:red;
  padding-top:2px;
  padding-bottom:2px;
  padding-left:6px;
  padding-right:6px;
  border-radius:4px;
  font-size:10.5pt;
}

a {
  color:white;
}

#topStuff {
  /* display:none; */
  color:yellow;
}

.hdr1 {
  color:white;
  text-decoration:underline;
}

h4 {
  color:blue;
  margin-top:4px;
  margin-left:4px;
  margin-bottom:6px;
  color:yellow;
}

.toggleEvtDetails {
  cursor:pointer;
  color:red;
}

#btnEventLogToggle {
  width:160px;
  overflow:hidden;
}

.lnk {
  background:lightyellow;
  cursor:pointer;
  border:solid red 1px;
  border-radius:3px;
  color:red;
  padding:2px;
  margin:6px;
}
              
            
!

JS

              
                const firstStackEntry = getJsStack().stackByIndex[0]; // make sure sitting on line 1 of Codepen JS panel!!!
const nCodeLineNumOffset = firstStackEntry.lineNum - 1;
let itemsByEndpoint = [];
let bBusyGettingApiData = false;
let sDataType = "planets";

let viewStack = [];
let evtLogging = [];
const sBaseUrl = "https://swapi.co/api/";
let sLastContentView;
const sSumColNames = ['climate','terrain','gender','director','producer','model','passengers','classification','designation'];

// API limit is 10,000 requests per day by IP. Might wanna chuck results in localStorage or something.


/*
 function runs when user changes data type in dropdown
 */
function changeDataType(cbo) {
  logEvt("changeDataType() called");
  const cboDataType = cbo;
  
  statusIs("changed top level query filter...");
  sDataType = cboDataType.value;
  getStarwarsData(sDataType, displayEndpointData);
} // end of function changeDataType()


function firstCap(sInput) {
  logEvt("firstCap() called");
  sInput = sInput.substr(0,1).toUpperCase() + sInput.substr(1,sInput.length-1).toLowerCase();
  return sInput;
} // end of function firstCap()


function getEndpointDataType(sEndpoint) {
  logEvt("getEndpointDataType() called. sEndpoint="+sEndpoint);
  const p1 = sEndpoint.indexOf("/");
  let sDatatype = "Library Entries";
  
  if (p1>-1) {
    logEvt("endpoint has a slash in it");
    sDatatype = firstCap(sEndpoint.substr(0,p1+1));
  } else {
    logEvt("endpoint is a top level endpoint");
    sDatatype = firstCap(sEndpoint);
  } // end if
  
  logEvt("data type being returned: "+sDatatype);
  return sDatatype;
} // end of function getEndpointDataType()



function getStarwarsData(sEndpoint, fn) {
  let entry = logEvt("called: getStarwarsData()");
  entry.description = "endpoint: "+sEndpoint;
  if (itemsByEndpoint[sEndpoint]) {
    entry.description = entry.description + "<br>returning a cached endpoint data object";
    let epd = itemsByEndpoint[sEndpoint];
    fn(epd);
    return epd;
  } else {
    logEvt("creating new endpoint data object");
    let endpointData = {};
    const p1 = sEndpoint.indexOf("/");
    endpointData.endpoint = sEndpoint;
    endpointData.dataRetrieved = false;
    endpointData.markup = "";
    endpointData.dataType = getEndpointDataType(sEndpoint);
    endpointData.dataTypeSingularForm = singularForm(endpointData.dataType);
    endpointData.currentPage = 0;
    endpointData.finishedGettingTopLevelData = false;
    endpointData.fn = fn;
    
    logEvt("adding endpoint data ojbect to cache array: itemsByEndpoint");
    itemsByEndpoint[sEndpoint] = endpointData;
    
    let sEndpoint2 = sEndpoint;

    if (p1===-1) {      
      // no slash found so...
      // must be a top level API call...
      endpointData.currentPage = endpointData.currentPage + 1;
      sEndpoint2 = sEndpoint2 + "/?page="+endpointData.currentPage+"&m=1";  
      entry = logEvt("top level endpoint, do a page query");
      entry.description = "page# to query:"+endpointData.currentPage; 
    } // end if
    
    getStarwarsDataFromApi(sEndpoint2, endpointData, fn)
    
    logEvt("returning endpointData object...");
    
    return endpointData;
  } // end if/else
} // end of function getStarwarsData()



function getStarwarsDataFromApi(sEndpoint, epd, fn) {
  statusIs("retrieving data for endpoint: <b>"+sEndpoint+"</b>");
  let sEndpoint2 = sEndpoint;
  const sFullUrl = sBaseUrl+sEndpoint2;
  
 // statusIs("Full URL: &nbsp;&nbsp;&nbsp;"+sFullUrl);
  
  try {
    logEvt("about to do a Fetch");
    
    fetch(sFullUrl)
      .then(response => {
        logEvt("got response object back");
        return handleResponse(response, sEndpoint, epd);
      }) 
    .then(rawData => {
      logEvt("got to .then(rawData");
      statusIs("data for endpoint: <b class='lbl'>"+sEndpoint+"</b> was retrieved");
      let data = rawData.results;
      if (epd.currentPage>1) {
        debugger;
      }
      
      if (!epd.data) {
        // get first batch of data for end point (it might be the only batch)
        logEvt("stashing first set of array data in epd object");
        epd.data = data;
        
        if (!Array.isArray(data)) {
          data.parent = epd;
        } // end if
      } else {
        logEvt("about to add array data returned from API call to epd object's existing array data");
        if (Array.isArray(data)) {
          let nMax = data.length;
          let n,itm;
          
          // copy new set of objects over to existing array of objects:
          for (n=0;n<nMax;n++) {
            itm = data[n];
            epd.data.push(itm);
          } // next n
        } // end if
      } // end if/else
      
      epd.dataRetrieved = true;
      
      
      if (Array.isArray(epd.data)) {
        logEvt("epd.data is an Array");
        processArrayData(epd.data);  
      } // end if
         
      logEvt("about to call function passed in as a parameter");
      fn(epd);
 
      if (epd.currentPage>0 && !epd.finishedGettingTopLevelData) {
        // attempt to load another "page" of top level data:
        statusIs("attempt to load another 'page' of top level data");
        debugger;
        epd.currentPage = epd.currentPage + 1;
        sEndpoint = epd.endpoint + "/?page="+epd.currentPage+"&m=1";
        getStarwarsDataFromApi(sEndpoint, epd, fn);
      } // end if
      
    }); // end of 'fetch' callback block
  } catch(err) {
    logEvt("JavaScript error caught");
    statusIs("Jedi Library Computer Error!");
    debugger;
  } // end of try/catch block
} // end of function getStarwarsDataFromApi()


window.addEventListener('load', pageSetup);




function handleResponse(response, sEndpoint, epd) {
  if (response.ok) {
    statusIs("response for endpoint: <b class='lbl'>"+sEndpoint+"</b> was retrieved");
    return response.json();
  } else {
    if (response.status === 404) {
      logEvt("page not found on API service");
      // page specified does not exist
      // there is no more pages of data to get for this end point
      if (epd.currentPage>1) {
        epd.finishedGettingTopLevelData = true;
        statusIs("Finished retrieving data");
        let fn = epd.fn;
        epd.currentPage = 0;
        fn(epd);
        return;
      } else {
        // other kinds of errors?
        logEvt("we ran into some other problem while doing the Fetch.");
      } // end if
    } // end if
    throw response;
  } // end if/else
} // end of function handleResponse()



function singularForm(sWord) {
  logEvt("called singularForm('"+sWord+"')");
  if (sWord === "Species") {
    return sWord; // leave the same
  } // end if
  
  if (sWord.substr(sWord.length-1,1) === "s") {
    sWord = sWord.substr(0,sWord.length-1);
    return sWord;  // ending 's' is removed
  } // end if
  
  if (sWord === "People") {
    return "Person"; // 
  } // end if
} // end of function singularForm()


function statusIs(sStatus) {
  const status = $("#status")[0];
  status.innerHTML = sStatus;
  
  logEvt(sStatus);
  
} // end of function statusIs()


function logEvt(sEventTitle) {
  let evtObj = {};
  
  evtObj.evtTimestamp = new Date();
  evtObj.eventTitle = sEventTitle;
  evtObj.stackInfo = getJsStack().stackByIndex;
  evtObj.expanded = false;
  evtObj.idx = evtLogging.length;
  evtObj.descr = "";
  evtObj.msSinceLastEvent = 0;
  
  if (evtLogging.length > 0) {
    let prevEvent = evtLogging[evtLogging.length-1];
    evtObj.msSinceLastEvent = evtObj.evtTimestamp.getTime() - prevEvent.evtTimestamp.getTime();
  } // end if
  evtLogging.push(evtObj);
  
  return evtObj;
} // end of function logEvt()


function toggleEventLog() {
  const btnEventLogToggle = $("#btnEventLogToggle")[0];
  const info = $("#info")[0];
  
  if (btnEventLogToggle.innerHTML === "View Event Log") {
    sLastContentView = info.innerHTML;
    btnEventLogToggle.innerHTML = "Close Event Log View";
    viewEventLog();
  } else {
    btnEventLogToggle.innerHTML = "View Event Log";
    info.innerHTML = sLastContentView;
  } // end if/else
  
} // end of function

function viewEventLog() {
  let s=[];
  const info = $("#info")[0];
  const nMax = evtLogging.length;
  let n,entry,sDisplay,n2,nMax2,stackEntry;
  
  s.push("<h4>JavaScript Code Event Log</h4>");
  s.push("<ul>");
  debugger;
  for (n=0;n<nMax;n++) {
    entry = evtLogging[n];
    sDisplay = "none";
    
    if (entry.expanded) {
      sDisplay = "inline";
    } // end if
    
    s.push("<li>");
    s.push("<span class='toggleEvtDetails' ");
    s.push("onclick='toggleEvtDetailsFn("+(n)+")' ");
    s.push(" title='click to expand/collapse event entry' ");
    s.push(">");
    s.push(entry.eventTitle);
    s.push("</span>");
      s.push("<ul id='evtDtl"+(n)+"' ");
      s.push("style='display:"+sDisplay+";'");
      s.push(">");
        s.push("<li>Milliseconds since previous log event: "+entry.msSinceLastEvent+"</li>");
        s.push("<li>Call Stack: ");
        s.push("<ul>");
        nMax2 = entry.stackInfo.length;
        for (n2=0;n2<nMax2;n2++) {
          stackEntry = entry.stackInfo[n2];
          
          if (stackEntry.funcName === "statusIs" || stackEntry.funcName === "logEvt") {
            break; // break out of the for loop
          } // end if
          
          
          
          s.push("<li>");
          s.push(stackEntry.funcName);
          s.push("()");
          s.push("&nbsp;&nbsp;&nbsp;&nbsp;Line Num: ");
          s.push(stackEntry.lineNum - nCodeLineNumOffset);
          s.push("</li>");
        } // next n2    
        s.push("</ul>");
    
        s.push("</li>");
      s.push("</ul>");
    s.push("</li>");
  } // next n
  
  s.push("</ul>");
  s.push("<hr>");
  s.push("<button onclick='clearEventLog()'>Clear Event Log</button>");
  info.innerHTML = s.join("");
} // end of function viewEventLog()



function toggleEvtDetailsFn(idx) {
  const entry = evtLogging[idx];
  const evtDtl = $("#evtDtl"+(idx))[0];
  
  if (entry.expanded) {
    evtDtl.style.display = "none";
    entry.expanded = false;
  } else {
    evtDtl.style.display = "inline";
    entry.expanded = true;
  } // end if/else
  
} // end of function toggleEvtDetailsFn()



function clearEventLog() {
  evtLogging = [];
  logEvt("Event Log Cleared");
  viewEventLog();
} // end of function clearEventLog()

/*
*/
function pageSetup() {
  const info= $("#info")[0];
  info.innerHTML = "<br>Starting up...";
  
 // const topStuff= $("#topStuff")[0];
  //topStuff.innerHTML = document.location;
  // "fullpage" - from pen browser
  // "boomboom" - refreshed version after pen change
  const cboDataType = $("#cboDataType")[0];
  changeDataType(cboDataType);
} // end of function pageSetup()



function displayEndpointData(epd) {
  logEvt("displayEndpointData() called");
  const info= $("#info")[0];
  let s=[];
  let itm;
  let n,nMax;
  let sFirstHdr = "Search Item";
  let ln1;
  
  if (epd.markup !== "") {
    info.innerHTML = epd.markup;
    return;
  } // end if
  
  let data = epd.data;
  

  if (Array.isArray(data) ) {
    logEvt("data variable is an Array");
    nMax = data.length;
    
    s.push("<h4>"+(nMax)+" &nbsp;&nbsp;"+epd.dataTypeSingularForm+" Records Were Found:</h4>");
    s.push("<table>");
    
    ln1 = data[0];
    
    if (nMax>0) {
      if (ln1.name) {
        sFirstHdr = epd.dataTypeSingularForm+" Name";
      } // end if
      
      if (ln1.title) {
        sFirstHdr = epd.dataTypeSingularForm+" Title";
      } // end if
    } // end if
    
    let nMax2 = sSumColNames.length;
    
    s.push("<tr>");
    s.push("<td nowrap><b class='hdr1'>");
    s.push(sFirstHdr);
    s.push("</b></td>");
    
    for (n=0;n<nMax2;n++) {
      if (ln1[sSumColNames[n]]) {
        s.push("<td nowrap><b class='hdr1'>");
        s.push(firstCap(sSumColNames[n]));
         s.push("</b></td>");
      } // end if
    } // next n
    
    s.push("</tr>");
    
    
    for (n=0;n<nMax;n++) {
      itm = data[n];
      s.push("<tr>");
            
      s.push("<td nowrap>&nbsp;&nbsp;");
      s.push("<span class='lnk' ");
      s.push(">");
      if (itm.name) {
        s.push(itm.name);
      } // end if
      
      if (itm.title) {
        s.push(itm.title);
      } // end if
      
      s.push("</span>");
      
      s.push("</td>");
      
      for (n2=0;n2<nMax2;n2++) {
        if (itm[sSumColNames[n2]]) {
          s.push("<td nowrap>");
          s.push(firstCap(itm[sSumColNames[n2]]));
          s.push("</td>");
        } // end if
      } // next n
      
      s.push("</tr>");
    } // next n
  } else {
    // non-array object
    logEvt("[data] is a non-array object");
  } // end if/else
  
  s.push("</table>");
  
  if (epd.currentPage === 0) {
    epd.markup = s.join("");
  } // end if
  
  info.innerHTML = epd.markup;
}// end of function displayEndpointData()


function processArrayData(arr) {
  logEvt("processArrayData() called");
  const nMax = arr.length;
  let n;
  let itm;
  let sEndpoint="";
 // statusIs("processArrayData() was called!");
  for (n=0;n<nMax;n++) {
    itm = arr[n];
    sEndpoint = "";
    
    if (typeof itm === "string") {
      logEvt("itm variable is a string");
      sEndpoint = getEndpointFromUrl(itm);
      
      if (!itemsByEndpoint[sEndpoint]) {
      } // end if
    } // end if
    
    if (typeof itm === "object") {
      logEvt("itm variable is a JavaScript object");
      fixItm(itm);
      
      sEndpoint = getEndpointFromUrl(itm.url);
      
      if (!itemsByEndpoint[sEndpoint]) {
        let endpointData = {};
        endpointData.endpoint = sEndpoint;
        endpointData.dataRetrieved = true;
        endpointData.data = itm;
        endpointData.markup = "";
        itm.parent = endpointData;
      } // end if
    } // end if
    
    
  } // next n
  logEvt("finished with: processArrayData() function");
} // end of function processArrayData()



function fixItm(itm) {
  logEvt("fixItm() called");
  fixDate(itm,"created");
  fixDate(itm,"edited");
} // end of function fixItm()



function getEndpointFromUrl(sUrl) {
  let entry = logEvt("getEndpointFromUrl() called");
  
  let sEndpoint=sUrl.substr(sBaseUrl.length, sUrl.length - sBaseUrl.length);
  
  entry.description = "Input URL: "+sUrl+"<br>Endpoint returned: "+sEndpoint;

  
  return sEndpoint;
} // end of function getEndpointFromUrl()




function fixDate(obj,sPropName) {
  logEvt("fixDate() called for property: "+sPropName);
  if (obj[sPropName]) {
    if (typeof obj[sPropName] === "string") {
      obj[sPropName] = new Date(obj[sPropName]);
    } // end if
  } // end if
} // end of function fixDate()



	function getJsStack() {
		try {
			thisWillThrowAnError.everyTime();
		} catch(err) {
			var stackDta = err.stack.split("\n");
			var stackInfo = {};
			var stack = [];
			var nMax = stackDta.length;
			var sValue,nPos,sValue2,sValue3;
			var n,stackEntry;
			
			stackInfo.timestamp = new Date();
			
			if (nMax>1) {
				for (n=1;n<nMax;n++) {
					sValue = stackDta[n];
					stackEntry = {};
					stackEntry.funcName = sValue.split("@")[0];
					sValue3 = sValue.split("@")[1];
					stackEntry.jsFileUrl = "";
					stackEntry.stackDepth = nMax - n;
					
          if (sValue3 == null) {
            sValue3 = sValue;
          } // end if
          
					nPos = sValue3.indexOf("?");
					
					if (nPos > -1) {
						stackEntry.jsFileUrl = sValue3.substr(0,nPos);
					} // end if
					
					sValue3 = sValue3.split(":");
					
					if (stackEntry.jsFileUrl === "") {
						// protocol plus rest of main url
						sValue2 = sValue[0] + ":" + sValue[1];
						
						if (sValue3.length-2 > 2) {
							sValue2 = sValue2 + ":" + sValue[2]; // handle port if there
						} // end if
						
						stackEntry.jsFileUrl = sValue2;
					} // end if
					
					
					stackEntry.column = sValue[sValue.length-1]-0;
					stackEntry.lineNum = sValue[sValue.length-2]-0;
					stack[stack.length] = stackEntry;
				} // next n
			} // end if
			
			stackInfo.stackByIndex = stack.reverse();
			
			return stackInfo;
		} // end try/catch
	} // end of function getJsStack() 
              
            
!
999px

Console