Taught by
Alexandra Ackerman
Code available at
https://github.com/newschool-webfundamentals
Presentations available at
newschool-webfundamentals.github.io
Last class, we talked about how JavaScript makes webpages interactive.
As a user, when I hover over a person I want to see information about them.
Accessing, modifying, and storing data (names of counties, vote count) are necessary for making pages interactive. Today we're going to dive into jQuery, which enables you to do those things with JavaScript.
The purpose of jQuery is to make it much easier to use JavaScript on your website.
In the same way that Materialize gave you CSS to style a page faster, jQuery gives you functions to interact with a webpage without having to write difficult "vanilla" JavaScript
Today we'll go over...in relation to jQuery
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects (elements) that you can interact with.
Imagine it as a tree-like representation of your HTML
The DOM acts as a family-tree of HTML nodes
Parents, children, siblings...
Once we understand how HTML is structured on the page (DOM), then we can search through the HTML to access elements
Before writing any code, we need to make sure the DOM is loaded on our page. If it isn't, jQuery won't be able to access the elements on the page
Use the jQuery function to get an element by a selector.
Once we have the element selected, you can call other functions like "text" to get the element's text
To modify the text, you pass a string argument to the text function
Functions with no arguments are usually "getters" in jQuery, ones with arguments are "setters"You can also use CSS selectors to get an element on the page. Sometimes you may not want all the "h1" elements on a page, but a specific one.
That's not what we want...
Use class to select an element
We can also use ID as a selector
You can also find elements by traversing the DOM
$("#destinations").find("li")
$("#destinations").find("li").first()
$("#destinations").find("li").last()
Remember how the DOM is like a family tree?
Access direct children of an elementOr access the parent element
In addition to modifying html text using text()
, you can add entire elements using jQuery
Now that we know how to access elements and modify them using getters and setters, let's talk about events.
$("li").first().text();
$("li").first().text("New text!");
$("ul").append("A new item ");
After the DOM has loaded, we listen to events on selectors and run a function when the event occurs
Let's look at some of the events you can listen to in the jQuery documentation
Before lab, let's go over an example of using jQuery events to trigger content changes on a page
Use jQuery to make an interactive page