WK5: Introduction to jQuery
Javascript Frameworks
Javascript frameworks came about as a way of extending “vanilla” Javascript primarily for two reasons:
- Dealing with cross-browser inconsistencies in DOM (Document Object Model) implementation.
- Creating more efficient ways of performing common tasks
Many Javascript frameworks exist, with various features and approaches to solving the above scenarios. Of these, jQuery has been for a significant time, the most popular. It is used by many of the largest companies and websites on the web.
What Is jQuery?
From the jQuery website:
jQuery is a fast, small, and feature-rich Javascript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write Javascript.
Using jQuery
Including jQuery in Your Page
You can get using jQuery very quickly by downloading jQuery from https://code.jquery.com/ or using their Content Delivery Network (CDN).
jQuery is a single .js file, that if you wish to run it, must be included just like any other external Javascript file in your HTML document. Any scripts that rely on jQuery must be included after jQuery.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Running Code on Document Ready
In vanilla Javascript, it is common to wrap code in an onload function to ensure the browser has loaded the document before the code executes:
window.onload = function() {
// ...
}
window.onload waits until all images have finished downloading. jQuery adds an event that allows code to be run as soon as the document is ready to be manipulated (without having to wait for images to download). Generally speaking, you should always put your jQuery code within a document ready function:
$( document ).ready(function() {
// Your code here.
});
jQuery Documentation
You can find explanations and examples of everything that jQuery can do at the API Documentation section of the jQuery website.
The $ Function
In any jQuery example you will see $ used as a function ($ is actually a perfectly valid function name). $() is actually a shorthand way of calling the main jQuery() function. Note that in any Javascript, no two functions can have the same name. Therefore the function $() must not already be in use, and sometimes you may see jQuery() used in place of this, simply to avoid conflicts.
Selecting Elements With jQuery
The method of selecting elements with jQuery is one of the greatest things about it. Whereas vanilla Javascript uses a bunch of different functions for selecting elements like document.getElementById(), document.getElementsByTagName() and document.getElementsByClassName(), jQuery uses a single function (the $ function) to select a set of elements that match a CSS selector (passed as a string parameter to the function). So for example, if I wanted to select a paragraph with the id of “output”, I could write:
<p id="output">Target me</p>
$( '#output' );
or I could select every direct descendant of the body element with a class of “section” like this:
$('body > *.section');
Any valid CSS selector is a valid jQuery selector!
jQuery Event Handling
jQuery makes detecting and reacting to browser events easy! The most flexible way of listening for events with jQuery is to use its .on() method. The code will look something like this:
$( 'someSelector' ).on( 'someEvent', function(e) {
// do something in response to the event
});
jQuery should be able to handle any of the standard HTML DOM events with the on function (using the event name as the first parameter).
For some event types, jQuery has shortcut methods for applying an event handler. For example, to react to click events, you can use jQuery’s click function like this:
$('#go').click(function(e) {
console.log('Hey');
});
You can find lots more examples of working with events at the jQuery API Documentation. Use the menu on the left to filter by event type (mouse events, keyboard events, browser events etc.)
Creating DOM Elements with jQuery
When passed a CSS selector, the $ function returns a set of matched elements, but we can also pass it an HTML string and it will return a new HTML element, which we can then insert into the DOM:
var myParagraph = $('<p>Some paragraph</p>'); // returns a paragraph element
Manipulating the DOM with jQuery
When we want to modify the content of an HTML element using vanilla Javascript, we modify its .innerHTML property:
document.getElementById("someId").innerHTML = "Some content";
jQuery provides much more flexible methods of DOM insertion, which you can find documented here.
The .html() jQuery method is most similar to the vanilla Javascript approach. When called on an element, the .html() method will insert whatever HTML string you pass it as a parameter into the element:
Note that if when called with no parameters, the HTML method returns the HTML string of the element on which it was called. Many jQuery methods have this dual behaviour, that allows you to set a value (by passing a parameter) and get a value (by passing no parameters) using the same method name.
jQuery also provides methods to .append() content at the end of an element, .prepend() content at the beginning of an element and .remove() an element from the DOM (among others).
See the Pen jQuery – Click to Add Circles by Michael (@michaelschmidt_) on CodePen.0
CSS Manipulation with jQuery
Modifying CSS styles using vanilla Javascript is just plain painful. jQuery offers a bunch of useful methods for getting and setting CSS-related properties of elements.
In the following, a slightly modified version of the previous example, the .addClass() and .toggleClass() methods are demonstrated.
See the Pen jQuery – Toggle Circles Green by Michael (@michaelschmidt_) on CodePen.0
Getting and Setting Attributes with jQuery
jQuery also makes it easy to get and set attributes on elements. Take for example, .attr() or .data(), which allow you to get or set general or more specific data attributes. Consider the below example. Combining these types of methods with the this keyword allows you more fine controlled behaviour for each element.
See the Pen jQuery – .data() and .click() by Michael (@michaelschmidt_) on CodePen.0
jQuery Animation Effects
jQuery enables support for simple animations. There are some built-in functions like fading and sliding, but you can also define your own animations using the .animate() method. The animate method takes as one parameter an object of CSS properties to animate, and as a second parameter a duration in ms for the animation to take. We recommend avoiding using jQuery do directly animate properties, as animating with CSS is much more performant. Always opt to do effects with CSS over Javascript where possible for the best results.
See the Pen jQuery – Toggle Display + Animation by Michael (@michaelschmidt_) on CodePen.0
Combining jQuery with CSS Classes
Although jQuery can animate between styles, creating animations by transitioning between CSS (classes using the transition CSS property) is often much more effective and puts less strain on the browser with smoother results. These techniques can of course be combined, however jQuery will animate CSS inline which naturally overrides and styles applied with classes (with exception of !important).
Extending jQuery
Many existing Web UI Frameworks (like Bootstrap) already use jQuery.
You can also extend jQuery with jQuery plugins. The official jQuery website hosts a plugin repository at http://plugins.jquery.com/ (though you can find others elsewhere).
There is also jQueryUI, which is “a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery Javascript Library.” It enables more complex interactions (like drag and drop, resize, sort etc), more complex effects (like colour animation and easing) and provides a bunch of themeable UI widgets.
jQuery plugins are included in a web page simply by including the plugin’s .js file. Just make sure you include it after you include jQuery itself:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!-- include jQuery first -->
<script src="js/jquery-3.2.1.min.js"></script>
<!-- include jQuery plugins next -->
<script src="js/someplugin.jquery.js"></script>
<!-- finally include your own scripts -->
<script src="js/main.js"></script>
</body>
</html>
jQuery plugins are usually well documented with demos and examples.
More jQuery Resources
While we have covered some of the more relevant parts of jQuery to this course here, there is more that jQuery can do. Here are some resources for digging deeper into jQuery:
- http://api.jquery.com/ – official jQuery documentation
- http://www.codecademy.com/en/tracks/jquery – interactive jQuery tutorials
- http://www.w3schools.com/jquery/
- jQuery tutorials at lynda.com
- http://jqfundamentals.com/chapter/jquery-basics
A list of more commonly used jQuery methods
- .addClass(), .removeClass(), .toggleClass() // For adding and removing classes
- .before(), .after(), .append(), .prepend(), .remove() // For adding and removing HTML elements
- .attr(), .data(), .prop(), .css(), .animate() // For getting and setting HTML attributes
- .parent(), .parents(), .children(), .siblings(), .find(), .prev(), .next() // For traversing and filtering your jQuery selection
- .text(), .html() // For editing the contents of an element
- .each() // Iterate over a jQuery collection and run a function for each element
- .on(), .click(), .resize(), .scroll() // Most common event handlers