3rd Party Libraries

As you've seen in a previous section it is possible to link to your code, as a ".js" file, from multiple html documents. This prevents you from having to write duplicate code across multiple documents and helps with maintainability and consistency in your code.

If you were to create an externally linked file that has multiple uses, then congratulations, you have creates a "library".

A Library is a pre-existing repositary of reusable code, possibly with a unique interface, that is designed to apply not to particular projects but to particular situations.

Eventually, in the natural process of learning about JavaScript, it might occur to you when creating your own reusable code that someone, somewhere, HAS to of already written the code that you are writing to accomplish a similar goal. In almost every situation, for almost any reason you can think of, this is in fact the case.

JavaScript, while powerful, just isn't always as concise as one might like. Imagine you are developing a web site that involves mathematical computations. Perhaps it is an accounting service, perhaps it is an instructional site for students, it doesn't matter. You will probably be writing higher math functions that basic JavaScript does not provide. In this case you would be in luck because many, many people have already found need for such code, written it, and share it freely online. So if you think writing your own code to find a square root or find the area of a hexagon is going to be very time consuming then consider searching online for a possible library to help.

On this page we'll be looking at some of the more popular libraries and giving short examples of what their purpose is and how they work.

As stated, for any of these libraries you will need to add a link to them in the header of your document, just as we would separate our own code into linked files to save space. Let's do that first. We'll use a link to the popular library "jQuery" for this example. It's simple enough and follows the stucture of the code below.



<html>
<header>

<!-- External libraries are typically linked within the header -->
<script src="jquery-2.1.4.min.js"></script>

</header>
<body>

<!-- content of this page -->
<div id="example_element"> </div>

</body>
<script>

// script to run that is specific to this page.
$( "#example_element" ).css( "background-color", "blue" );

</script>
</html>

In this case we 1. created a link to a JS file containing the code library we want to work with and 2. made use of that library by invoking jQuery specific commands to change the color of an element in the document.

It should be noted that it is possible to link to an external file that does not necessarily exist within your own web space. While it can save a *small* amount of space on your end to use public files it does make your site dependent on those public files always being online. You can read more about how to use public libraries at the following link for Google's own hosted libraries (and find usable links to their versions as well).

Google Hosted Libraries

The HTML above should now be easy enough to understand, so let's look at that one line of jQuery in particular.

jQuery

jQuery is one of, if not the most, popular libraries available for general JS development. It does not target one particular facet of JavaScript development but tries to create shortcuts for the operations and precedures that you use the most.

So while you may not be using jQuery to calculate advanced trigonometry or power the animation of your browser based video game - it can be very useful to condense an operation like gathering a list of elements for editing very quickly.

Here's a simple example of what we're talking about.



// Here we get an element from the html section of a document, one
// with an id of "example_element_1" and
// change the background color using plain JavaScript that can be
// read without other dependencies.

var target = document.getElementById( "example_element_1" );
target.style.backgroundColor = "red";

// If we wanted to we could condense this code a bit to fit it onto a single line.

document.getElementById( "example_element_2" ).style.backgroundColor = "green";

// Now let's look at how we can do the same exact thing using
// jQuery...

$( "#example_element_3" ).css( "background-color", "blue" );

The individual parts of that last line can be broken down like this.

  • The "$" symbol and the argument after it acts as a "catch all" shortcut to grab an element id or class (elements referenced by id always include the "#" sign). This replaces "getElementById" and "getElementsByClass".
  • The "$" symbol also returns the element as an object automatically. So we can immediately edit a property of it such as CSS styling by adding ".css()". This replaces the "element.style." part of the longer, basic code.
  • Finally the "background-color" and "blue" strings withing the parenthesis are a simple property / value pair that replaces the "backgroundColor = x" section of the original code. This is the code that can access a stylistic property as it would actually be written within a CSS style section.
  • You can see how the second piece of code has a few advantages over the first. Most obvious is the fact that the second example is somewhat shorter. You might also have noticed that the reference to the background color style is also written as it would be in an actual CSS section, with a hyphen in between the two words, and not as it is written in basic JavaScript where CSS properties and written in camel case.

    What else can this library do?

    
    
    // Here's an example of some code that will create a new
    // element when the user clicks a pre-existing element.
    
    // Bind a "click" event to a particular div.
    // The detected even will run an anonymous function.
    $( "#jq_button" ).click( 
    	function(){
            // The anonymous function will create a new
            // div element within our HTML body area.    
            $( "target_element" ).append("<div class='example_square'><p>Your new element.</p></div>");
    	}
    );
    
    // Note how in each of these jQuery methods, like "append", the
    // contents of the method are written as strings within
    // quotation marks.  This is essentailly markup written as
    // plain text.
    
    

    Here is an example that uses code similar to the above, only it is designed to an a new element to this text box instead of the body of the page.

    Click Me!

    There are two very important notes on syntax to keep in mind when writing code such as the above.

    • A string sent into a method as an argument must be written on a single line. Some browsers will not collapse the white space of method parameters since the string we are sent in will be parsed "as is". In other words, in this case, we can't write out the "<div>" and "<p>" tags on separate lines.
    • When a string contains quotations within it you must alternate double and single quotation marks. With the example above we wrote the string for the argument of "append" within double quotations so we can not write the class name given to the new element with double quotations as well. If we did the string would think it ends earlier than it should. Using single quotes around "example_square" is a valid way of writing quotes within quotes.

    Rermember, these rules will be true for most aspects of JavaScript, not just jQuery.

    jQuery Minified

    If you followed the earlier link to the jQuery website and attempted to download it you may have noticed multiple options in the download section. Obviously the different version numbers indicate which version is the most recent but there's also an option for uncompressed or compressed (Minified) versions.

    What is the minified version? Essentially it is the same code that has had all extrenuous lines removed (such as comments), has had some lines compressed, and which results in a smaller and faster to download file.

    Let's look at how a piece of JavaScript, written in basic JavaScript can be minified.

    The idea is that this...

    
    
    // Grab the target element.
    var target = document.getElementById( "example_element_x" );
    
    // Define a color to use.
    var color = "red";
    
    // Assign the color to our element.
    target.style.backgroundColor = color;
    
    

    ...can be simplified to this:

    
    
    document.getElementById( "example_element_x" ).style.backgroundColor = "red";
    
    

    The same concept exists for the minified version of jQuery. The code that makes up the library has been truncated and shortened in a way that would make it less readable to the human eye - but at the sime time would make it much faster to obtain and process from a web link.

    In all other aspects the code will work the same way.

    Three.js

    "Three.js" is a library designed to help with implementation of advanced 2D and 3D graphics within a web browser. It makes heavy use of "WebGL", which is a standardized way your browser can implement instructions to any 3D hardware that might be found on your system. If no suitable hardware is found, or is too weak, then web sites that use WebGL may not run well - or at all.

    For the example below we will simply make a pair of cubes, one that has a solid color for a surface and another that uses an image for the surface, and have them animate in a very simplistic rotation.

    The code comments will contain an explanation of everything required. It is presuming that the actual "three.js" library file has been downloaded and loaded within the current document.

    
    
    ////////////////////////////////////////////////////////////////////////////////
    // Environment set up
    
    // Every Three.js scene will need some basic elements.
    // Primarily you will always use...
    // a "scene" object to hold all objects you want to show,
    // a "camera" object to tell three.js where the point of view is from, and 
    // a "renderer" object which actually interfaces with the hardware in your computer.
    
    // Create a new scene object.
    var scene = new THREE.Scene();
    
    // Create a new perspective camera (as opposed to an orthogonal camera).
    // The paramters are FOV, aspect ratio, and the near and far clipping planes.
    // Only objects between the near and far planes will be drawn.
    var camera = new THREE.PerspectiveCamera( 80, 1.7, 0.05, 1000 );
    
    // If we wanted the window to automatically size to the possible space of the 
    // browser window we can use the "window" keyword, like so...
    //var camera = new THREE.PerspectiveCamera( 80, window.innerWidth / window.innerHeight, 0.05, 1000 );
    
    // Create a new renderer object.
    var renderer = new THREE.WebGLRenderer();
    
    // For the renderer we need to set a window size.
    // We could skip this line, but three.js will use a default size anyway.
    renderer.setSize( 800, 450 );
    //renderer.setSize( window.innerWidth, window.innerHeight );
    
    // And add the window to the DOM.  After this line you'll be able to actually 
    // see the three.js window element within your HTML upon inspection.  If you 
    // want the window to appear elsewhere, you simply append the object to the
    // desired parent element.
    // document.body.appendChild( renderer.domElement );
    
    document.getElementById('three_box').appendChild( renderer.domElement );
    
    // The width and height of the viewport are defined by this parent object.
    // The renderer willa automatically size itself to fill this space.
    
    ////////////////////////////////////////////////////////////////////////////////
    // Cube 1
    
    // Now we can add objects to the scene to create our particular image.
    
    // We'll start with a simple geometric object - a cube.
    var geometry_01 = new THREE.BoxGeometry( 3, 3, 3 );
    
    // Objects will need materials, here we add a solid color to use.
    // This will produces a flat shaded object we WON'T be applying an image to.
    var material_01 = new THREE.MeshLambertMaterial( { color  	: "rgb(100%, 100%, 100%)" } );	
    
    // There are other material options.  If we wanted only a colored object
    // without lighting lighting onformation we could also use "MeshBasicMaterial".
    //var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );	
    
    // Keep in mind many tutorials will use hexadecimal for color values.  For instance...	
    // 0xFFFFFF is equal to white.
    // 0xff0000 is red.
    // Feel feel to use them.  If you're a masochist.
    
    // Geometry alone can not be rendered, that geometry needs to contain a "mesh" object.
    // This defines the actual polygons and materials used with the object.
    var cube_01 = new THREE.Mesh( geometry_01, material_01 );
    
    // We can set the position fo the cube within the scene with the "position.set"
    // method.  The parameters are simply x, y, and z coordinates.
    cube_01.position.set(-2.5, 0, 0);
    
    // Now that we have all the pieces in place we can add the full object to the scene.
    scene.add( cube_01 );
    
    ////////////////////////////////////////////////////////////////////////////////
    // Cube 2
    
    // Our second cube will make use of a simple texture map.  For that we need
    // to load and assign the texture to this reference.
    var texture = new THREE.TextureLoader().load( "z/chicken_512.jpg" );
    
    // If the texture had been stored in a subfolder then the path would have been:
    // loadTexture('folder/chicken.jpg')
    
    // "three.js" material methods take a LOT of parameters, there are 24 
    // possibilities!  Luckily, because of the way three.js is built, you can mix 
    // and match the parameters by sending them in as one large JavaScript object 
    // list.  Here are two that are pretty much required.
    
    var material_02 = new THREE.MeshLambertMaterial({
    			// On a mapped object the "color" parameter is overridden.
    			side 	: THREE.DoubleSide,
    			map		: texture
            	});
    			
    // If repeating textures are needed we can do that via the "repeat" option
    // of the "texture" object.
    /*
    texture.wrapS = THREE.RepeatWrapping;
    texture.wrapT = THREE.RepeatWrapping;
    texture.repeat.set( 1, 1 );
    */	
    
    // The rest of our code will follow the same format as it was written for box 1.
    
    var geometry_02 = new THREE.BoxGeometry( 3, 3, 3 );
    var cube_02 = new THREE.Mesh( geometry_02, material_02 );
    cube_02.position.set(2.5, 0, 0);
    scene.add( cube_02 );
    
    ////////////////////////////////////////////////////////////////////////////////
    // Lighting
    
    // To be able to see the object we will also need a light withint he scene.
    // The parameters are color, intensity, distance, and decay (optional).
    // Note how we can also use a scale of 0-255 for the RGB values instead of percentages.
    var light_01 = new THREE.PointLight( "rgb( 255, 255, 255)", 1, 100 );
    
    // Set the position of the light within the world coordinates.
    light_01.position.set( 10, 10, 5 );
    // In three.js, light will only affect objects using "MeshLambertMaterial" or "MeshPhongMaterial"
    // material types.
    
    // Add the actual light to the scene.
    scene.add( light_01 );
    
    // Let's add another light just we can see the entire cube.  But this one will be a different color.
    // For this last light lets look at another way of defining colors.
    
    // By making a new color via the three.js interface we can create a "Color" 
    // object.  It takes three floating point numbers that range from 0 to 1 for 
    // the RGB values.
    var light_02_color = new THREE.Color( 1, 0, 0 );
    
    // Now we can make the light.
    var light_02 = new THREE.PointLight( light_02_color, 1, 100 );
    light_02.position.set( -10, -10, 5 );
    scene.add( light_02 );
    
    // Set the initial position of the camera so that we can see the cube (which we
    //  left at 0,0,0).
    camera.position.z = 5;
    
    ////////////////////////////////////////////////////////////////////////////////
    
    // Since rendering 3D imagery is VERY taxing compared to most web sites which 
    // don't even require GPU hardware we should take into account the time it takes 
    // to actually process the image.  This means using the so called delta time to 
    // render our scene based on the amount of time since the last rendering 
    // happened.
    var time_old = Date.now();
    var time_new;
    var t;
    
    // The JavaScript object that actually calls your upadtable functions.
    var myInterval = setInterval(get_time, 0);
    
    function get_time() {
    	// Get the current time.
        time_new = Date.now();
    	
    	// The time since the last frame is the new time minus the old time.
        t 		 = time_new - time_old;
    	
    	// Make the old time into the new time for the next pass after this one.
        time_old = time_new;
    
    	// Run the actual loop function that will be both update and draw.
    	// You could separate this into two functions if desired.
    	loop(t);
    }
    
    // The actual update loop.
    // This is where we'll do all of the logic and drawing that we need to.	
    function loop (t) {
    	
    	// requestAnimationFrame will set a request for another frame to be drawn after this one.
    	// This is akin to setTimeout in normal JavaScript.
    	//requestAnimationFrame( render );
    
    	// Here we can implement instructions for our scene.  Moving objects, game logic,
    	// whatever it may be.  It could happen here.
    	cube_01.rotation.x += 0.001 * t;
    	cube_01.rotation.y += 0.001 * t;
    	//cube.rotation.z += 0.025;
    
    	cube_02.rotation.x -= 0.001 * t;
    	cube_02.rotation.y -= 0.001 * t;
    	
    	// Every frame you need to call the renderer to update an internal draw function.
    	// This is where the renderer object we made actually looks at the scene and camera
    	// objects to decide what, and where, everything needs to be drawn.
    	renderer.render(scene, camera);
    };
    
    

    And here we have the same code actually running...

    React

    "React" is a JavaScript library designed to help specifically with the development of interfaces.

    Follow the link to the right to go to the homepage.

    Content TBD.

    Content TBD.

    Content TBD.