cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

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.

            
              <h1>JavaScript Quick Reference</h1>

<hr>
<div class="nav">
  <h4>Working With DOM</h4> 
  <ul>
    <li><a href="#accessing">Accessing the DOM</a></li>
    <li><a href="#siblings">Grab Children/Parent Node(s)</a></li>
    <li><a href="#createDom">Create DOM Elements</a></li>
    <li><a href="#addDom">Add Elements to the DOM</a></li>
    <li><a href="#classList">Add/Remove/Toggle/Check Classes</a></li>
  </ul>
</div>
<div class="nav">
  <h4>Working With JS</h4> 
  <ul>
    <li><a href="#array">Add/Remove Array Item</a></li>
    <li><a href="#addProp">Add/Remove Object Properties</a></li>
    <li><a href="#conditional">Conditionals</a></li> 
    <li><a href="#loops">Loops</a></li>
    <li><a href="#events">Events</a></li>
    <li><a href="#timers">Timers</a></li>
    <li><a href="#type">Type Checking</a></li>
  </ul>
</div>
<div class="nav">
  <h4>Working With Functions</h4> 
  <ul>
    <li><a href="#default">Add Default Values to Function</a></li>
    <li><a href="#throttle">Throttle Functions on Resize</a></li>
  </ul>
</div>

<!-- Accessing Dom Elements -->
<section id="accessing" class="section">
  <h3><i>Accessing Dom Elements:</i></h3>
<pre class="syntax">
<code>
//Returns a reference to the element by its ID.
document.getElementById(id);

//Returns an array-like object of all child elements which have all of the given class names.
document.getElementsByClassName(names);

//Returns an HTMLCollection of elements with the given tag name. 
document.getElementsByTagName(name);

//Returns the first element within the document that matches the specified group of selectors.
document.querySelector(selectors);

//Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) 
//that match the specified group of selectors. 
document.querySelectorAll(selectors);</code>
</pre>
  <a class="up"  href="#">Top</a>
</section>
<!-- /Accessing Dom Elements -->


<!-- Grab Children/Parent Node(s) -->
<section id="siblings" class="section">
  <h3><i>Grab Children/Parent Node(s):</i></h3>
<pre class="syntax">
<code>
//Get child nodes
var stored = document.getElementById('heading');
var children = stored.childNodes;
console.log(children);

//Get parent node
var parental = children.parentNode;</code>
</pre>
  <a class="up"  href="#">Top</a>
</section>
<!-- /Grab Children/Parent Node(s) -->


<!-- Create New DOM Elements -->
<section id="createDom" class="section">
  <h3><i>Create New DOM Elements:</i></h3>
<pre class="syntax">
<code>
//create new elments
var newHeading = document.createElement('h1');
var newParagraph = document.createElement('p');

//create text nodes for new elements
var h1Text= document.createTextNode("This is the fucking header text!");
var paraText= document.createTextNode("This is the fucking Paragraph text!");

//attach new text nodes to new elements
newHeading.appendChild(h1Text);
newParagraph.appendChild(paraText);

//elements are now created and ready to be added to the DOM. </code>
</pre>
  <a class="up" href="#">Top</a>
</section>
<!-- /Create New DOM Elements -->
  
  
<!-- Add Elements to the DOM -->
<section id="addDom" class="section">
  <h3><i>Add Elements to the DOM:</i></h3>
<pre class="syntax">
<code>
//grab element on page you want to add stuff to
var firstHeading = document.getElementById('firstHeading');

//add both new elements to the page as children to the element we stored in firstHeading.
firstHeading.appendChild(newHeading);
firstHeading.appendChild(newParagraph);

//can also insert before like so

//get parent node of firstHeading
var parent = firstHeading.parentNode;

//insert newHeading before FirstHeading
parent.insertBefore(newHeading, firstHeading);</code>
</pre>
  <a class="up" href="#">Top</a>
</section>
<!-- /Add Elements to the DOM -->  

<!-- Add Elements to the DOM cont-->
<section class="section">
  <h3><i>Add Elements to the DOM cont.:</i></h3>
<pre class="syntax">
<code>
//Suppose you have the following HTML
&lt;div id="box1">
    &lt;p>Some example text&lt;/p>
&lt;/div>
&lt;div id="box2">
    &lt;p>Some example text&lt;/p>
&lt;/div>

//you can insert another snippet of HTML between #box1 and #box2 
var box2 = document.getElementById("box2");
box2.insertAdjacentHTML('beforebegin', '&lt;div>&lt;p>This gets inserted.&lt;/p>&lt;/div>');

//beforebegin - The HTML would be placed immediately before the element, as a sibling.
//afterbegin - The HTML would be placed inside the element, before its first child.
//beforeend - The HTML would be placed inside the element, after its last child.
//afterend - The HTML would be placed immediately after the element, as a sibling.</code>
</pre>
  <a class="up" href="#">Top</a>
</section>
<!-- /Add Elements to the DOM cont. -->  


<!-- Add/Remove/Toggle/Check Classes -->  
<section id="classList" class="section">
  <h3><i>Add/Remove/Toggle/Check Classes:</i></h3>
<pre class="syntax">
<code>
//grab element on page you want to use
var firstHeading = document.getElementById('firstHeading');

//will remove foo if it is a class of firstHeading
firstHeading.classList.remove("foo");

//will add the class "anotherClass" if one does not already exist
firstHeading.classList.add("anotherclass");

//add or remove multiple classes
firstHeading.classList.add("foo","bar"); 
firstHeading.classList.remove("foo","bar");

// if visible class is set remove it, otherwise add it
firstHeading.classList.toggle("visible");

//will return true if it has class of "foo" or false if it does not
firstHeading.classList.contains("foo");</code>
</pre>
  <a class="up" href="#">Top</a>
</section>
<!-- / Add/Remove/Toggle/Check Classes -->  


<!-- Add/Remove Array Item -->  
<section id="array" class="section">
  <h3><i>Add/Remove Array Item:</i></h3>
  <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" >Array docs</a>
<pre class="syntax">
<code>
//create an empty array
var myArray = [];

//create array with items. Can store any type
var myOtherArray = [myArray, true, "A random string"];

//call specific value in an array
myOtherArray[0];
//will return myArray

//change value for this item
myOtherArray[0] = false;
//will now return false


//add to end of array
myOtherArray[myOtherArray.length] = "new stuff";
//will return the new item "new stuff"

//or you can use push()
myOtherArray.push("new stuff");
//will return new length of array


//you can remove this last item by using pop()
myOtherArray.pop();
//will return the last item of the array and will have removed it from myOtherArray


//shift and unshift will do the same for the begging of the Array
myOtherArray.shift();
//will remove and return first item of array

myOtherArray.unshift(1,2);
//this will add 1 and 2 to beginning of array and return new length

//you can use delete keyword but turn value to undefine and not shorten length. so we use splice()
myOtherArray.splice(2, 1);
//this will remove and return  the third item only. 
//first arg is where to start and second is how many things to splice. this example is 1.</code>
</pre>
  <a class="up"  href="#">Top</a>
</section>
<!-- /Add/Remove Array Item --> 


<!-- Adding/Removing Properties in Object --> 
<section id="addProp" class="section">
  <h3><i>Adding/Removing Properties in Object</i></h3>
<pre class="syntax">
<code>
//create an object
var newObject = {};

//add a property to object
newObject.newPropName = "super fly";

//or other syntax
newObject['other new prop name'] = "mildly fly";

//Now newObject.newPropName will return super fly
newObject.newPropName;

//now to delete
delete newObject.newPropName;</code>
</pre>
  <a class="up" href="#">Top</a>
</section>
<!-- / Adding/Removing Properties in Object --> 


<!-- Conditionals --> 
<section id="conditional" class="section">
  <h3><i>Conditionals:</i></h3>
<pre class="syntax">
<code>
//If Else statements
var a = 1;
varb b = 2;

if( a < b ) {
  console.log('the if is true!');
} else {
  console.log('the if is false!');
}


//Multi If Else statements
var a = 1;
varb b = 2;
varb c = 3;

if( a > b ) {
  console.log('the if is true!');
} else if(a > c) {
  console.log('OK, THIS if is Ture!');
} else {
  console.log('None of these were true');
}


//Ternary operators. same as if else
var a = 1;
varb b = 2;

a === b ? console.log('The statement is true) : console.log('The statement is false');


//switch statements. 
var a = 4;
switch (a) {
  case "Oranges":
    console.log("Orange? really?");
    break;
  case 1:
    console.log("a is equal to 1.");
    break;
  case 2:
    console.log("a is equal to 2.");
    break;
  case 3:
    console.log("a is equal to 3.");
    break;
  case 4:
    console.log("a is equal to 4.");
    break;
  default:
    console.log("I run if no one else is true.");
}</code>
</pre>
<a class="up"  href="#">Top</a>
</section>
<!-- /Conditionals -->   
  

<!-- Loops -->   
<section id="loops" class="section">
  <h3><i>Loops:</i></h3>
<pre class="syntax">
<code>
//while loop
var i = 0;
while( i < 10 ) {
  console.log(i);
  i += 1
}


//do while loop
var i = 0;
do {
  console.log(i);
  i += 1
} while( i < 10 )


//for loop
for ( var i = 0; i < 10; i++ ) {
   console.log(i);
}

//for in statments
var obj = {a:1, b:2, c:3};
    
for ( var prop in obj ) {
  //check if property is inherited or not
  if(obj.hasOwnProperty(prop)) {
    console.log("obj." + prop + " = " + obj[prop]);
  }
  
}</code>
</pre>
<a class="up"  href="#">Top</a>
</section>
<!-- /Loops -->   


<!-- Events -->     
<section id="events" class="section">
  <h3><i>Events:</i></h3>
  <a href="https://developer.mozilla.org/en-US/docs/Web/Events">Event Reference</a>
<pre class="syntax">
<code>
var newElement = document.getElementsByTagName('h1');

newElement.onclick = function() {
  console.log('clicked');
};

newElement.addEventListener("focus", function(event) {
    console.log('focused');
}, false);

newElement.removeEventListener("focus", function(event) {
    console.log('focused');
}, false);


window.onload = function() {
  console.log("Im loaded");
};</code>
</pre>
  <a class="up"  href="#">Top</a>
</section>
<!-- /Events --> 


<!-- Timers -->   
<section id="timers" class="section">
  <h3><i>Timers:</i></h3>

<pre class="syntax">
<code>
function simpleMessage() {
  alert("This is just a simple alert");
}

//set time out
window.setTimeout(simpleMessage, 5000);

//if you wanted to clear the timer.
var timer = window.setTimeout(simpleMessage, 5000);
window.clearTimeout(timer);

//set interval. will repeat every  5000ms
window.setInterval(simpleMessage, 5000);

//if you wanted to clear the intervals.

var intervalHandler = window.setInterval(simpleMessage, 5000);
window.clearInterval(intervalHandle);</code>
</pre>
  <a class="up"  href="#">Top</a>
</section>
<!-- /Timers -->   
  

<!-- Type Checking -->     
<section id="type" class="section">
  <h3><i>Type Checking:</i></h3>

<pre class="syntax">
<code>
var myNumber = 1;
var myString = "some Text";
var bools = true;
var myArray = [];
var myObj = {};
var notNumber = NaN;
var nullified = null;

typeof myNumber;
//returns "number"

typeof myString;
//returns "string"

typeof bools;
//returns "boolean"

typeof myArray;
//returns "object". 

//Not super helpful so must check if it has length property to see if it is an array.
typeof myArray === 'object' && myArray.hasOwnProperty('length');
//returns true

typeof myObj;
//returns "object". Must do the same test as above but expect false back from check.

typeof notNumber;
//returns "number". this is confusing but returns this as NaN is part of the global Number object.

//must check if isNaN()
typeof notNumber === 'number' && isNaN(notNumber);
//returns true if type of is "number" and is still NaN</code>
</pre>
  <a class="up"  href="#">Top</a>
</section>
<!-- /Type Checking -->  
  
  
 
<section id="default" class="section">
  <h3><i>Add Default Arguments for Function:</i></h3>
<pre class="syntax">
<code>
//you provide defaults inside your function

var myFunction = function myFunction(arg1, arg2) {
  var arg1 = (typeof arg1 !== 'undefined') ? arg1 : "default argument one";
  var arg2 = (typeof arg2 !== 'undefined') ? arg2 : "default argument two";
  console.log(arg1 + " & " + arg2);
};</code>
</pre>
  <a class="up" href="#">Top</a>
</section>
  

  
  
<section id="throttle" class="section">
  <h3><i>Throttle Functions on Resize:</i></h3>
  <a href="https://developer.mozilla.org/en-US/docs/Web/Events/resize">Mozilla</a>
<pre class="syntax">
<code>
var optimizedResize = (function() {

  var callbacks = [];
  var running = false;

  // fired on resize event
  function resize() {

    if (!running) {
      running = true;

      if (window.requestAnimationFrame) {
        window.requestAnimationFrame(runCallbacks);
      } else {
          setTimeout(runCallbacks, 66);
      }
    }

  }

  // run the actual callbacks
  function runCallbacks() {
    callbacks.forEach(function(callback) {
      callback();
    });
    running = false;
  }

  // adds callback to loop
  function addCallback(callback) {
    if (callback) {
      callbacks.push(callback);
    }
  }
  
  return {
    // initalize resize event listener
    init: function(callback) {
      window.addEventListener('resize', resize);
      addCallback(callback);
    },
    // public method to add additional callback
    add: function(callback) {
      addCallback(callback);
    }
  }
  
}());

// start process
optimizedResize.init(function() {
    console.log('Resource conscious resize callback!')
});</code>
</pre>
  <a class="up" href="#">Top</a>
</section>  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

<div id="template">
<div class="keywords"> 
function
break
case
catch
continue
debugger
default
delete
do
else
finally
for
function
if
in
instanceof
new
return
switch
this
throw
try
typeof
var
void
while
with
case
catch
const
debugger
default
do
enum
export
extends
finally
import
super
switch
throw
try
abstract
boolean
byte
case
catch
char
class
const
debugger
default
do
double
enum
export
extends
final
finally
float
goto
implements
import
instanceof
int
interface
long
native
package
private
protected
public
short
static
super
switch
synchronized
throw
throws
transient
try
volatile
abstract
boolean
byte
char
class
const
debugger
double
enum
export
extends
final
float
goto
implements
import
int
interface
long
native
package
private
protected
public
short
static
super
synchronized
throws
transient
volatile
class
enum
export
extends
import
super
implements
interface
let
package
private
protected
public
static
yield
</div>
<div class="colortheme">
#936565
#C48686
#8E574D
#BA7D67
#AD713E
#C69060
#99701F
#B59140
#9B954B
#BCB23B 
#808E42
#9EB25F 
#539B53
#75BC75
#42845D
#5EAA7D
#0F8776 
#00A99D
#138591
#4FA4B2
#0071BC
#4DA0CE
#3062AA
#6291BF
#5462B5
#7696DD
#5E57B5
#7D7DD8
#7A5E99
#9787AD
#955AA3
#AC85B5
#A05A89
#B780A8
</div>
</div>
            
          
!
            
              @import "compass/css3";

$blue: #0095dd;
$red: #e74c3c;

body {
  background: #ecf0f1;  
}

h1 {
  color: $blue;
  font-size: 2.25em;
  font-weight: bold;
  line-height: 1.2;
  text-align: center;
}



hr {
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #fff;
}

ul a { 
  text-decoration: none; 
  &:hover { text-decoration: underline; }
}

.nav {
  display: inline-block;
  vertical-align: top;
  
  h4 { text-align: center; }
  
  a {
    color: #333;
    font-size: .85em;
  } 
}

.section {
  padding: 1.5em;
  
  h3 {
    color: $blue;
    display: inline-block;
    font-size: 1em;
  }
  
  a {
    color: #333;
    font-size: .85em;
  } 
  
  .up { color: $red; }
}


//code styles
.syntax{
  background: #f4f7f8;
  color: #558ABB;
  margin: 10px 0;
  border:solid thin #ddd;
}
.syntax span{
  counter-increment: linecounter;
}
.syntax span:before{
  content: counter(linecounter);
  width: 1.2em;
  text-align:center;
  display: inline-block;
  border-right: 1px solid #ddd;
  margin-right: 10px;
  font-style:normal !important;
  color:#555 !important;
}
#template {
  display: none; }

.num {
  font-weight: 600;
  color: #d0782a; }

[class*=var] {
  font-weight: 600; }

.clr {
  border-radius: 1px;
  color: white;
  font-weight: 400; }

.str, .str i {
  color: #ddca7e !important;
  font-weight: 400 !important; }

.reg, .reg i {
  color: #ddca7e !important;
  font-weight: 500 !important}

.cmnt, .cmnt i {
  color: #bbb !important; 
  font-weight: 400 !important; }

@media (max-width: 400px) {
  .syntax {
    font-size: 12px; } 
}
            
          
!
            
              
//text highlighting completely from https://codepen.io/bisk8s/pen/LGfBh
$().ready(init);

var $syntax
  , tokens = []
  , token_colors = {}
  , refresh_timer
    // Characters that separate tokens
  , rx_splitters = /[\s\+\-=\*\(\)\{\}\[\]\.;\|,\!]/g
  , rx_splitters_string = "([\\s\\+\\-=\\*\\(\\)\\{\\}\\[\\]\\.;\\|,\\!])"
    // Match comments
  , rx_comments = /(\/\/(.*))\r?\n|\r/g
    // Match "strings", 'strings', and /regexes/
  , rx_strings = /("(.*?)")|('(.*?)')|(\/([^\s]+?)[^\\]\/[a-z]*)/g
    // Match #hex colors
  , rx_colors = /(#[0-9a-fA-F]{6})/g
    // Match numbers
  , rx_numbers = /([\s\+\-=\*\(\)\{\}\[\]\.;\|,\!])([0-9]+)([\s\+\-=\*\(\)\{\}\[\]\.;\|,\!])/g
    // Match valid characters: letters, numbers, _underscore, $
    // but don't let first character be a number
  , rx_allowed =  /(^[a-zA-Z_\$][a-zA-Z0-9_\$]*)/
  ;

function init() {
  // Get selectors
  $syntax = $(".syntax");
  //
  init_theme();
  init_keywords();
  //
  update();
}

function update() {
  $syntax.each(function () {
    // Insert cursor placeholder
    //insertTextAtCursor("@" + "@");
    //
    var text = $(this).text();
    // Process text
    text = process(text);
    $(this).html(text);
  });
}

function process(string) {
  var html = string;

  assign_colors(string);

  var rx_tokens = make_regex(tokens, "g");


  html = htmlify(html);

  html = html
          .replace(rx_strings, replace_rx_strings)
          .replace(rx_tokens, replace_tokens)
          .replace(rx_comments, replace_rx_comments)
          .replace(rx_numbers, replace_rx_numbers)
          .replace(rx_colors, replace_rx_colors)
          ;
  html = applyLineNumbers(html);
  return html;
}

// ==============================
function applyLineNumbers(string){
  string = string.split(/\n/);
  string = string.join('</span>\n<span>');
  string = '<span>'+string+'</span>';
  return string;
}

function assign_colors(string) {

  var split = string.split(rx_splitters);

  var old_colors = token_colors;
  token_colors = get_uniques(split);
  tokens = Object.keys(token_colors).sort();

  var len = tokens.length;

  for (var i = 0; i < len; i++) {

    var percent = i / len;
    var index = parseInt( (percent * 132) + (Math.random() * 0) );

    if (index < 0) index = 0;
    else if (index > 99) index = index - 99;
    else if (index > 66) index = index - 66;
    else if (index > 33) index = index - 33;

    var color = "var" + index;
    token_colors[tokens[i]] = color;
  }
}


// ==============================

function get_uniques(arr) {
  var uniques = {};
  for (var i = arr.length - 1; i >= 0; i--) {
    if ( arr[i].length > 0
          && rx_allowed.test(arr[i])
          && !keywords.test((" " + arr[i] + " "))
    ) {
      uniques[ arr[i] ] = true;
    }
  };
  return uniques;
}

// ==============================

// Make a regex that finds any word in the array between splitter characters

function make_regex(arr, flags) {
  var str = "(" + arr.join("|").replace(/\$/g,"\\$") + ")";
  str = rx_splitters_string + str + "(?=" + rx_splitters_string + ")";
  var regex = new RegExp(str, flags);
  return regex;
}


// ==============================


function replace_rx_comments(match, p1, p2, p3, offset, string) {
  return "<i class='cmnt'>" + match + "</i>";
}

function replace_rx_strings(match, p1, p2, p3, offset, string) {
  var cls;
  if (match.charAt(0) == "/") cls = "reg";
  else cls = "str";

  return "<i class='" + cls + "'>" + match + "</i>";
}

function replace_rx_colors(match, p1, p2, p3, offset, string) {
  var clr =  "<i class='clr' style='background: ";
      clr += match + "; box-shadow: 0 0 0 2px " + match + "; ' >";
      clr += match + "</i>";
  return clr;
}

function replace_rx_regexes(match, p1, p2, p3, offset, string) {
  return "<i class='reg'>" + match + "</i>";
}

function replace_rx_numbers(match, p1, p2, p3, offset, string) {
  return p1 + "<i class='num'>" + p2 + "</i>" + p3;
}

function replace_tokens(match, p1, p2, p3, offset, string) {
  var colorclass = token_colors[p2];
  return p1 + "<i class='" + colorclass + "'>" + p2 + "</i>";
}

// ==============================

function init_theme() {
  var node = document.querySelector(".colortheme");
  var colors = node.innerHTML.trim().split("\n");
  
  var css = "";
  for (var i = 0; i < colors.length; i++) {
    css += ".var" + i + "{color:" + colors[i] + ";} ";
  }
  add_style_sheet(css);
}

// ==============================

function init_keywords() {
  var node = document.querySelector(".keywords");
  var kw_list = node.innerHTML.trim().split("\n");
  keywords = make_regex(kw_list,"");
}

function add_style_sheet (css) {
  var head, styleElement;
  head = document.getElementsByTagName('head')[0];
  styleElement = document.createElement('style');
  styleElement.setAttribute('type', 'text/css');
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = css;
  } else {
    styleElement.appendChild(document.createTextNode(css));
  }
  head.appendChild(styleElement);
  return styleElement;
}

function contains(str, substr) {
  return str.indexOf(substr) !== -1;
}

function htmlify(str) {
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}

function unquote(str) {
  return String(str).replace(/"/g, '&quot;');
}
            
          
!
999px
Close

Asset uploading is a PRO feature.

As a PRO member, you can drag-and-drop upload files here to use as resources. Images, Libraries, JSON data... anything you want. You can even edit them anytime, like any other code on CodePen.

Go PRO

Loading ..................

Console