We have updated the content of our program. To access the current Software Engineering curriculum visit curriculum.turing.edu.
jQuery Intro, DOM Traversal, Bootstrap styling
Learning Goals
- Student can navigate and select/alter content on an HTML page using jQuery
- Begin recognizing patterns involved with using jQuery
- Explain what jQuery is, and it’s benefits
Vocabulary
- selector
- DOM
- DOM Manipulation
- DOM Traversal
Warm Up
How do you as a user know how to interact with a website?
What is the DOM?
The DOM, or Document Object Model, represents how HTML is read by the browser. It allows JavaScript to manipulate, structure, and style your website. After the browser reads your HTML document, it creates a representational tree called the Document Object Model
and defines how that tree can be accessed.
Manipulating the DOM refers to changes that are made in the browser, that are prompted but not directly made by the user. If I type my email in a form then click “Submit”, I might see a message like “Thanks for signing up!”. I clicked the button and in response, JavaScript made that message appear. That is an example of DOM manipulation. Today we will learn how to change something on our site based on user interaction.
Access Elements from the DOM
JavaScript has some built-in functions that allow us to access elements from the DOM. Here’s an example of accessing an h1 element.
var header = document.querySelector('h1');
console.log(header);
//=> "<h1>hello</h1>"
Let’s break this down:
document
- this tells the computer: please go over to the HTML document.querySelector
- now that the computer is looking at the HTML document, this instruction says: I’d like you to look for something specific('h1')
- this is the argument passed to the .querySelector function. It says: go look in the HTML document for the first h1 that you find.
Since we stored the value of this in the header variable, we can console.log()
this and see the HTML element.
We can also access elements by selectors (classes and IDs). Instead of (‘h1’) we would need to write something like ('.class-name')
or ('#id-name')
, using the same selectors we would when writing CSS rules for classes or IDs.
What is jQuery?
jQuery is a library that allows us to access DOM elements on the page and then interact with them. Under the hood, it’s JavaScript. Since it is just JavaScript, it is executed in the browser. It is used by 97.4% of all the websites whose JavaScript library we know. This is 73.9% of all websites. It is currently being used by Google, Microsoft, Quizlet, Home Depot, and more.
In addition to providing a syntax that makes reading and writing code easier and faster, jQuery is used to improve browser compatibility.
First Lines of jQuery
Let’s say that we have a page with the following markup:
<h1 class="important-header">Dinosaurs are awesome.</h1>
Just like with vanilla JavaScript, jQuery lets us change the text programatically. The neat thing about jQuery, though, is that it significantly reduces the amount of code we have to write.
document.querySelector('h1').innerText = 'I AM A DINOSAUR.'); // vanilla JS
$('h1').text('I AM A DINOSAUR.'); // jQuery
Try It
Play around with the CodePen below using jQuery:
- Open the example below in CodePen using the `Edit on CodePen` button in the top right corner.
- Change the replacement text to something else.
- Change the
h1
selector to.important-header
- Add the following line of code:
$('h1').css('color', '#FC17A5');
See the Pen Dino 1 by Michael Dao (@mikedao) on CodePen.
Fun Fact: Accessing DOM elements by ID and element is much faster than by class.
Responding to User Events
jQuery and, of course, JavaScript are used to change and manipulate web pages. Just like JavaScript, jQuery has the ability to add event listeners based on user interaction.
DOM Manipulation is the crux of front-end engineering. We present a user interface and then as the user interacts with the UI, we change and update what the user sees.
Let’s take a look at the jQuery syntax and then we’ll talk about what’s happening.
Open the example below in CodePen using the Edit on CodePen
button in the top right corner.
See the Pen Dino 2 by Michael Dao (@mikedao) on CodePen.
The following things are happening in the example above:
- We’re querying for any elements with the class of
change-me
. - We’re adding an
event listener
to those elements. (There is just one in this case.) - We’re listening for a user’s mouse click.
- We’re providing an anonymous function.
- In this example, the function will add a line through the
h1
and add text to theh2
.
Now, when a user clicks on that button, the browser will run the function we provided to the event listener!
We can also listen for things other than clicks. Here are some other events from the jQuery documentation:
click
contextmenu
dblclick
hover
mousedown
mouseenter
mouseleave
mousemove
mouseout
mouseover
mouseup
Take a moment to investigate and play with some of them.
Adding a CSS Class
Open the example below in CodePen using the Edit on CodePen
button in the top right corner.
See the Pen Dino 3 by Michael Dao (@mikedao) on CodePen.
We’re using a jQuery method called toggleClass()
. When the user clicks on the button, it either adds or remove the class upside-down
depending on whether or not it was already there.
Try It
First, fork this CodePen to your account so you can edit it.
- Can you create some additional CSS classes and toggle them?
- Can you also change the text?
- Try out the following methods:
toggle()
,slideToggle()
,fadeToggle()
.
Getting Values from the User
We’re getting somewhere! We can respond to actions and change elements. It would be cool if we could also get some information from the user. If you recall, HTML provides <input>
elements for just this kind of situation. jQuery helps out by providing the .val()
method for getting the value out of a selected <input>
element.
Open the example below in CodePen using the Edit on CodePen
button in the top right corner.
Let’s explore the following example:
See the Pen Dino 4 by Michael Dao (@mikedao) on CodePen.
Turn & Talk
Talk through each line of JavaScript. For the parts that are new - make your best guess as to what the code is doing. For the part that are review - use precise technical vocabulary to explain what the code is doing.
A Note on Working with Numbers
JavaScript has two ways of seeing if two values are equal: ==
and ===
. ==
is notoriously weird, so we tend to avoid it. But there is something with using ===
and getting numbers from input fields that we need to discuss.
Open the example below in CodePen using the Edit on CodePen
button in the top right corner.
Let’s consider the following example:
See the Pen Game 1 (Non-Working) by Michael Dao (@mikedao) on CodePen.
Hmm—that’s curious. It doesn’t seem to work. You may have encountered this in a previous project. No matter what, input fields always hold strings of text. So, we’re actually getting the string "2"
from the input element and not the integer 2
. It makes sense that those things are not strictly equal. What we need to do is turn that string into a number before we compare it.
This is pretty common, so JavaScript gives us a function for doing it called parseInt()
.
parseInt("2") === 2; // true!
Now, we can update our conditional as follows:
if (parseInt(number) === 2) {
$('.message').text('You are right!');
} else {
$('.message').text('Sorry, that is not the number 2.');
}
It works now!
See the Pen Game 1 (working) by Michael Dao (@mikedao) on CodePen.
Event Object
Consider a situation where we have three boxes. When that particular box is clicked, we want to toggle a class on that box only. How do we know which box was clicked?
It turns out that when we add an event listener using jQuery, we get access to the event
object. The event object is a JavaScript object that represents the event (think click, mouseover, etc.) that triggered the listener. We typically name this variable event
or e
. We are provided with many properties and methods on the object. Most commonly used is the target
property. The CodePen and Try It sections below will illustrate what it information it provides us with.
Open the example below in CodePen using the Edit on CodePen
button in the top right corner.
Let’s take a look at the example below:
See the Pen event object by Amy Holt (@ameseee) on CodePen.
Try It: Event Object
Fork the CodePen above, then implement the following functionality:
- When the user hovers over a given box, that box appears to grow in size.
- When the mouse leaves that hover state, that box returns to its original size.
Traversing the DOM
The event
object comes with a lot of properties and methods that we can use to our advantage. In the example above, we wanted to target the element that was clicked on, so used e.target
. jQuery also allows us to find an element in relation to the element we clicked. When the browser parses our HTML, it creates a big tree-like structure. jQuery lets us hop from branch to branch.
Where will we need this? In a classic To-Do List, we want to be able to click a delete button associated with a to-do, then have that entire to-do deleted.
Let’s work through a box example again. We want each box to have a button inside of it. When the user clicks the button, it should rotate the entire box. (We’re rotating the box with a CSS class called clicked
.)
See the Pen Rotating Buttons by Michael Dao (@mikedao) on CodePen.
This code does not work the way we’d like - right now when we click on the button, the button itself is rotating instead of the entire box. What we need to do is when the user clicks on a button, go up and find the box that it lives in (the parent element) and add the class to that element.
Try It: DOM Traversal
Do some research and work to make the entire box rotate, rather than just the button.
You can see all of ways we can move around the DOM tree in jQuery documentation.
Implementation
Now that you’ve had some time to familiarize yourself with jQuery, let’s implement it into a real application.
Practice
Fork this CodePen and write jQuery to make this a working ToDo List.
Interview Questions
- What is jQuery?
- Why is jQuery needed?
- What are the advantages of jQuery?