jQuery

Objectives

  • Describe jQuery and its purpose as a JavaScript library
  • Understand the benefits and drawbacks of using jQuery.
  • Practice using jQuery selectors

What is jQuery?

jQuery is a 3rd-party library that is intended to make front-end development tasks --- particularly those involving DOM selection and manipulation --- easier, faster, and more fun.

But wait, what do we mean by 'library'?

A library is a collection of reusable functions that serve a particular purpose. The great thing about libraries is that we're using code that solves common problems, thus avoiding reinvention of the wheel.

So, as a library, what does jQuery offer us?

jQuery helps us manipulate the DOM, allowing us to perform complex manipulations using less code with less hassle. jQuery's syntax was developed to mimic CSS selector syntax, making code easier to develop, read, and manage; also, the syntax is more concise, and jQuery solves many cross-browser compatibility issues for us.


jQuery - DOM Manipulation

Installation

jQuery is a client side library, which means we need to include it in our HTML. To do this, we have two options:

  • Reference jQuery from a server on the internet. CDNs (content delivery network) like CDNJS or Google Hosted Libraries
  • Download a copy of jQuery to host on your own server:

CDNJS, Google Hosted Libraries, and the jQuery site will all allow you to download a copy of jQuery to include in your projects.


DOM manipulation with jQuery

To select an element in the DOM, we use the global jQuery function:

// This is the basic syntax for jQuery selections
$(' ')

// To select a particular element by tag, you do
$('h2') // selects all h2 elements

// To select by ID, you use the same syntax as CSS selectors
$('#someID') // Would select the element with ID="someID"

// To select all elements of a particular class, use CSS syntax again
$('.someClass') // Selects all elements of the class "someClass"

// And you can use more complicated CSS selectors as well
$('p.anotherClass') // Selects all <p> tags that also have the class "anotherClass" (<p class="anotherClass">)

If you use variable assignment when doing a selection, a "jQuery" object is returned

var paragraphs = $('p'); // Returns a jQuery object containing all <p> tags on your web page.

Selecting a DOM element and changing it's content

In this HTML:

<div id="myDiv">Hello world!</div>
// vanilla JavaScript, using the browser API
var divToManipulate = document.getElementById('myDiv');
divToManipulate.innerHTML = "Goodbye world!";

Now the code above isn't too hard to deal with, but even so, in jQuery, this is a one-liner.

$('#myDiv').html("Goodbye world!");

If we wanted to save our selection as a jQuery object, the code would look like this instead:

  • First we select the element we want and save it as a jQuery object
var taco = $('#taco');
  • Then we use our jQuery object to perform our task
taco.html("Goodbye world!");

There are three things about the example above that make jQuery easier to use:

  1. jQuery is using the same syntax as CSS to select elements
  2. jQuery allows us to chain methods together to accomplish our goals (i.e., $().html(...) ), making code shorter and easier to understand
  3. jQuery deals with any cross-browser compatibility issues, which may not seem like a big deal in this example, but which quickly become difficult to deal with as things get more complex

Appending a DOM element to a web page

If we had the following HTML page...

<html>
<body>

  <div id="container"></div>

</body>
</html>

If we want to add a new DIV that provides a nice greeting, our vanilla JavaScript would have to be:

  var myDiv = document.getElementById('container');
  var newP = document.createElement('p');
  newP.innerHTML = "Hello complicated, multi-step world of adding an element to the DOM!";
  myDiv.appendChild(newP);

And in jQuery, it looks like this:

  var newP = $('<p>');
  $('#container').append(newP)
  newP.append("Hello simple insertion using jQuery chaining");

In the jQuery code example above, we create a new paragraph element, then select the DIV with `id="container"`` and we append. We then append the text we want to insert to the new paragraph element we just created. In effect, the new HTML looks like this after the jQuery is run:

  <div id="container">
    <p>
      Hello simple insertion using jQuery chaining
    </p>
  </div>

Adding and Removing Elements Using jQuery

Sometimes in a dynamic web application, user-input is meant to trigger the addition or removal of content or functionality. Using jQuery, we can easily create new DOM elements and insert them into the DOM, or remove existing elements (and any content they contain) from the DOM.

So, let's imagine we have a web page with the following content on it:

<body>
  <div id="outerContainer">
    <div class="innerItem innerItemHeader">Enjoy some hipster ipsum:</div>
    <div class="innerItem">
      Aesthetic migas paleo McSweeney's, pork belly Kickstarter Echo Park sriracha keytar disrupt viral drinking vinegar fanny pack typewriter.
    </div>
  </div>
</body>

Let's say we want to add some more hipster ipsum to the page. Something like:

<div class="innerItem">
  Farm-to-table Godard roof party bespoke, fashion axe mustache vinyl.
</div>

To add this DIV, and our hipster ipsum content using jQuery, we'd do the following:

Define a new DIV and assign jQuery object to $newDiv

var hipsterIsum = $('<div>');

// Add hipster ipsum content
hipsterIsum.html("Farm-to-table Godard roof party bespoke, fashion axe mustache vinyl.");

// Set it's class to innerItem
hipsterIsum.addClass("innerItem");

// Append our new element
$('#outerContainer').append(hipsterIsum);

jQuery - Styles

You can do more than select elements and modify content. You can also create or update CSS style attributes in jQuery using the .css() method

$("#myDiv").css("color", "red");

Or, if we have a bunch of elements that all have the same class (in this example, it's class="myClass"), we can use the class selector to modify the color of all of them at once:

$(".myClass").css("color", "blue");

But that seems kind of boring. I mean, what if we want to do something with less hard-coding using jQuery.

var randColorValue = function() {
  return Math.floor( Math.random() * 255 );
}

var randColor = function() {
  var red = randColorValue();
  var green = randColorValue();
  var blue = randColorValue();

  return "rgb(" + red + "," + green + "," + blue + ")";
}

$(".myClass").css("color", randColor());

results matching ""

    No results matching ""