Web Design Primer
Chapter 10 – JavaScript Libraries
A JavaScript library is a collection of function that speed up the development of a web site. There are a range of libraries available and many have strong communities that assist in improving the functionality and supporting users. This chapter provides an overview of popular libraries and how you can get started with them.
When choosing a library, it is important to assess your application requirements and experience. Some libraries lack documentation, especially if newly released. Mature libraries have an advantage when it comes to community support, documentation, and life-cycle. Younger libraries may be short-lived or require code to be rewritten when new versions are released. However, the benefit of a younger library is that they often employ novel approaches and may be more efficient in execution. Also check for corporate backing when looking at a library. This ensures the code will continue to be supported and updated.
In this chapter, we will look at jQuery (mature) and Vue.js (emerging/young).
For the purpose of this book, a JavaScript library is a single file that can be included with your code and provides several functions for your use. This differs from a framework, which is more opinionated on how you develop your entire site and relies on multiple files. Frameworks often provide both frontend and backend code. A JavaScript plugin extends a library to provide added functionality. Plugins rely on a library, whereas libraries are self-sufficient.
List of JavaScript Frameworks
List of JavaScript Libraries
Getting Started with a JavaScript Library
The standard is usually to download the library and move the files into your development folder. This process makes sense when you’re developing without an internet connection or if you’re creating a standalone website for an internal network. What makes the web so powerful is its inter-connectivity. So why not leverage this? Why don’t we just link to a host that already has the file so we have less to manage in our files and folders. But don’t just use any host, use a Content Delivery Network.
Content Delivery Networks (CDN)
CDN’s are servers that are typically used to host assets so that sites aren’t bogged down serving them. The advantage is that they are located all over the world, so if a user connects to your website, they can be served assets (images, videos, static code) from the server closest to them. We still need our own server for anything that’s dynamic, meaning anything that changes often. If you’re running a database, you can package what the user needs, while have them download assets elsewhere. The result is a quicker load time.
Another advantage of a CDN is caching. Let’s say your user visits a WordPress blog and is given the jQuery file from a CDN called Cloudflare. Then your user heads over to your site and you’ve linked to the same jQuery file on Cloudflare. The browser has already downloaded it, so there’s no point in downloading it again, it will just use the version it already has. CDNs typically store each version of a file in a separate folder so it will never expire. Your browser caches files for a set period of time before it downloads again. The expiry date can be specified by the CDN to be a very long time.
We’ll be showing you how to use a CDN to use jQuery and Vue.js
jQuery
Released in 2006, jQuery is the most popular JavaScript Library online. Thousands of plugins exist and their documentation and community support is extensive.
To start, you can find the latest version of jQuery on a cdn.js. Simply find the min (minified) version and copy the script tag.
The code you’ve copied should be placed in your HTML document before the closing body tag:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </body> </html>
Once that’s completed, you’re ready to write your first line of jQuery code!
Here’s an example of a button that shows and hides all paragraphs in a document:
<!DOCTYPE html> <html> <head><title>Button Toggle</title></head> <body> <button>Click on me</button> <p>This text will appear and disappear when you click the button</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $('button').click( function() { $('p').toggle(); } ); </script> </body> </html>
One of the benefits of jQuery is its use of CSS-like targeting to control your interactions. To target an element, we just use its name, in this example, it’s button. We then specify the interaction as a click. The function that follows runs when the button is clicked and targets the all paragraph elements on the page to toggle. By switching out toggle for slideToggle, we can animate the paragraphs to vertically slide in and out of view.
Try changing the toggle to slideToggle and adding more paragraphs to the document. Then load the page in a browser and click on the button to see jQuery’s magic in action. Another function to try is fadeToggle.
jQuery Counter
To create a counter, we will need to use a variable to hold the current count. The counter will be set to zero by default. Each time a button is pressed, it will increment by one and the value will be output in HTML. To do this, we need to specify the output location and the button. Instead of using HTML elements (button, p or a), we will use id attributes.
For counting down, instead of using the jQuery click function, the onclick attribute will be used on the button element. A function called subtract() will need to defined in JavaScript.
<button id="add">+</button> <button onclick="subtract()">-</button> <p id="output">Number appears here</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> // Setup the variable and output it counter = 0; $('#output').html(counter); // Adds 1 when the button with id='add' is clicked $('#add').click( function() { counter++; // same as counter = counter + 1; $('#output').html(counter); } ); // Subtracts 1 when the button with the onclick="subtract()" is clicked function subtract() { counter--; // same as counter = counter - 1; $('#output').html(counter); } </script>
Vue.js
As an up-and-coming library, Vue.js has excelled due to its ease-of-use and efficiency. The syntax is cleaner compared to jQuery, but you’ll be polluting your HTML with new attributes specific to Vue. This means the separation of HTML and JavaScript is less apparent. The benefit is how fast Vue is at updating the Document Object Model (DOM). Think of the DOM as the HTML Lego blocks that are used to construct your website. Each block is accessed and acted upon by JavaScript. If you have a lot of code and lots of content updates, the browser will be working harder to traverse (scan your code) and make relevant updates. Vue has a very efficient means of performing updates compared to jQuery.
Just like jQuery, including Vue.js is as simple as a script element link from a CDN.
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
Hello Name Example
<div id="example"> <input type="text" placeholder="Enter your name" v-model="username"> <h1>Hello <span v-html="username">Sample Name</span>!</h1> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script> <script type="text/javascript"> new Vue({ el: '#example', data: { username: '' } }) </script>
In the above example, we must first define a div to run our example. All HTML that will be acted upon will be nested within the div. The input element as an attribute of v-model, which is a Vue.js attribute that allows us to link the input content to the span element with an attribute of v-html. Notice that both have a value of username, allowing the input and the span to relate to each other.
In JavaScript, we’ve specified the location where Vue.js will be focusing its efforts (#example). By default, the username is set to nothing. Notice how the “Sample Name” is removed when the page loads. We override the content when Vue.js loads our data.
Vue.js Counter
<div id="counter"> <button v-on:click="number++">+</button> <button v-on:click="number--">-</button> <p v-html="number">Number appears here</p> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script> <script type="text/javascript"> new Vue({ el: '#counter', data: { number: 0 } }) </script>
There is no need to explicitly output the number. Vue.js handles this because it’s directly linked to the v-html attribute. We’ve also skipped the need to define a function because we can run an arithmetic process directly on a click action. For more complex operations, a function can be called using v-on:click=”functionName”. We’ve done away with about 10 lines of code using Vue.js compared to jQuery.