jQuery

jQuery Overview

  • JavaScript's Role and the DOM
  • Introducing jQuery and Selectors
  • jQuery Methods
  • jQuery Events
  • Method Chaining
  • jQuery with Forms

Reading Assignment

Please read Chapters 5 - 7

javascript textbook cover

JavaScript's Two Main Roles

  1. DATA: Retrieve, Change, and Store Data
  2. UI: Change how the UI looks based on the data or based on what the user is doing.

jQuery is a library that helps us do #2, change the UI and respond to user-driven events.

Kalediscope

What is a user-driven event?

Anytime a user scrolls, clicks, hovers, or types in a form field, we want something to change on the screen.

Sometimes, we only want to change one thing on the screen. We want the browser to only change that one thing in the UI, not reload the entire site.

Before we start!

Let's talk about how the browser actually reads your code....

HTML and JavaScript were not written to interact with each other.

Trying to hit a nail

Solving the problem

  • Browsers contain an API (Application Programming Interface) that allows your JS and HTML to interact.
  • The programming API for documents (aka web pages) is called the Document Object Model (DOM).

The DOM

  • The Document Object Model is the bridge between your JS and your HTML.
  • Think back to how data talk to each other over the internet. What data type would we need for interactions? Objects! Document Object Model!!!
  • The browser's API (the DOM) turns each HTML tag into a JS object, and each of those objects is stored inside the DOM.

DOM Activity on the Document

  1. Press command-option-J to open JavaScript console in Dev Tools.
  2. In the console, type: document;
  3. Press return.
  4. Then click the dropdown arrow in the result that shows. What do you see?
  5. Try clicking on nested dropdown arrows. What do you see?
  6. Does the code look familiar? Yes, what you see is what we often see in the Elements tab when we open Dev Tools Inspector!

What is the DOM?

We have explored the D for Document.

We have explored the O for Object.

What about the M for Model?

The DOM

Terminology

The DOM
  • The DOM, just like JavaScript objects, is a data structure called a "tree."
  • Each point of data is called a "node."
  • Each "node" can have a "parent", "child", and/or "sibling" nodes.
  • The DOM is accessed by a global variable called document.
  • Because the DOM stores information as JS objects, we can use "dot notation" to access methods and properties.

Reading Assignment

Please read Chapter 5

javascript textbook cover

jQuery Overview

  • JavaScript's Role and the DOM
  • Introducing jQuery and Selectors
  • jQuery Methods
  • jQuery Events
  • Method Chaining
  • jQuery with Forms

What is jQuery?

jQuery is a collection of JavaScript code. This is called a library.

A library is a collection of reusable methods for a particular purpose. (Like Bootstrap for CSS)

jQuery uses the DOM to find the nodes to apply JS.

What is jQuery?

JQuery is JavaScript.

Benefits to using jQuery

How to write jQuery

jQuery has its own syntax, which we will cover.

To use jQuery (just like Bootstrap in CSS), we add the jQuery library (or CDN) script tag into the HTML file.

Best practice:
Put the script tag right before the closing body tag.

How to write jquery

HTML example

Hosted Libraries

Google has a website for all of the links needed to add JavaScript Libraries.

Go to Hosted Libraries.

  1. Then find the contents sidebar on the right to click on "jQuery".
  2. Copy the most recent snippet by triple clicking on that line of code to paste into your project. (next slide)
  3. Before you leave, you can add this hosted libraries link to your Bookmarks Bar.

Root Folder Activity

Let's create a project that employs our jQuery CDN.

  • Create a project titled "jQuery Intro" in Visual Studio Code that has HTML, CSS, JS files and/or folders.
  • In your HTML file, paste the jQuery CDN.
  • Then create at least 3 elements in the body tag (e.g., breakfast options, grocery list, greeting).
  • Congratulations! You've just created a project with elements that can be selected using jQuery! Save this project. We will add more to it later.

How to write jQuery

                        
$("HTML-element-selector")
  • Step 1: Let the JavaScript engine know that you are using the jQuery library by writing the $ sign.
  • Step 2: Identify which HTML element you want to modify or attach an event to.
  • Step 3: Select that element using the selector method from CSS.

How to write jQuery

  • Step 4: Apply a jQuery method.
                        
$("HTML-element-selector").method();

Notice for the selector, the parentheses must accept a string as a parameter.
Notice the dot notation for methods to call.
Notice that parentheses are used to call the method.

HTML & jQuery

Here is an HTML element:


<div id="greeting">Hello!</div>

jQuery selecting that HTML element:

                        
$("#greeting")

You can use a selector just like the id selector in CSS.

HTML & jQuery

Here is an HTML element:


<div class="greeting">Hello!</div>

jQuery selecting that HTML element:

                        
$(".greeting")

You can use a selector just like the class selector in CSS.

jQuery: selecting elements

Write out the jQuery selector for each of the following HTML elements. Click forward to see the answer!

                      

Welcome!

Welcome!

Welcome!

Welcome!

How to Select HTML Elements

jQuery Overview

  • JavaScript's Role and the DOM
  • Introducing jQuery and Selectors
  • jQuery Methods
  • jQuery Events
  • Method Chaining
  • jQuery with Forms

jQuery Methods Activity

Check this out!

Then do this mix and match!

jQuery Overview

  • JavaScript's Role and the DOM
  • Introducing jQuery and Selectors
  • jQuery Methods
  • jQuery Events
  • Method Chaining
  • jQuery with Forms

User Events with jQuery

Once an HTML element is selected as a jQuery selector, we can then use jQuery methods to change it.

For example, when you click on a button, you want the button to do something (e.g., hide/show, alert, tooltip).

Another example: when you submit a form, you want the form to clear its contents.

jQuery Events

In addition to changing elements when the document loads or depending on certain media queries, we also need to change the UI based on events.

Events are when the user takes an action on your site. Examples: clicks a button, types in a form, hovers over a link, scrolls down the page, etc.

Action!

jQuery Events

You can use the .on() method to create certain events!

                        
$("img").on("click", function() {
    //let's do something!
});

Are there different events that you can use instead of just "click"?

In this Codepen, use the .show() and the .hide() methods to change the paragraphs!

jQuery Events

 
$("button").on("click", function(){ 
    $("button").css("background-color", "blue")
});

Color My Boxes Exercise

Change my Color -- use this jsfiddle link.

When the user clicks the "Red" Button, the text "Change My Color" should be changed to red.

When the user clicks the "Blue" Button, the text "Change My Color" should be changed to blue.

Exercise Gif Trello Logo

Fadein Exercise

Start a root folder. Add your libraries and links. Here is the HTML you can add to your HTML file:

       
<button id="clicker">Click me to show a hidden secret!</button>
<div id="secret" style="display: none">I am a hidden secret.</div>

See next slide for details.

Fadein Exercise

  • Challenge 1: Add jQuery code that fades in the text "I am a hidden secret" whenever the button is clicked.
  • Challenge 2: Change your jQuery code so it slides down the text instead of fading it in.
  • Challenge 3: Change the button text to say "Click me to toggle a hidden secret!" and make the text toggle between fading in and out each time it is clicked.
Exercise Gif Trello Logo

Reading Assignment

Please read Chapter 6

javascript textbook cover

jQuery Overview

  • JavaScript's Role and the DOM
  • Introducing jQuery and Selectors
  • jQuery Methods
  • jQuery Events
  • Method Chaining
  • jQuery with Forms

Method Chaining

Instead of writing :

                                   
$(".warning").hide();
$(".warning").fadeIn(3000);
          

You can write:

                                   
        $(".warning").hide().fadeIn(3000);
        

As long as you are using the same selector, you can chain multiple methods.

Notice the semi-colon is after the last method in the chain.

May the force be with you! Exercise

Study the code first! The CSS has been written for you.

Code Pen Challenge here.

Exercise Gif Trello Logo

In-class practice

  • Create a button in HTML that says “Click me!” and has an ID of “movie”
  • When the button is clicked, you want to ask the user what their favorite movie is.
  • Store the user’s answer in a variable called favFilm.
  • Log the variable favFilm to the console.

jQuery Overview

  • JavaScript's Role and the DOM
  • Introducing jQuery and Selectors
  • jQuery Methods
  • jQuery Events
  • Method Chaining
  • jQuery with Forms

Working with forms

.on() with the argument "submit" must be applied to a form element and tells the browser to submit every input that user has entered into an input field.

                        
$("form").on("submit", function(e){
    e.preventDefault(); //this prevents the form from refreshing
    var number = $("input").val(); // this allows us to store the value input by the user into a variable.
    console.log(number);
});
        

Notice .on() accepts two arguments here, a string and a function.

Submitting a Form

Explain the following code, line by line.

  
//Version 1
$("#user-form").on("submit", function(e){
    e.preventDefault()//This prevents the form from refreshing the page and wiping all of the user's inputs.
    var userEmail = $("#user-email").val();
    $("div.welcomeBox").append("

Welcome "+ username + "

") }); //Version 2 $("#submit-button").on("click", function(e){ e.preventDefault()//This prevents the form from refreshing the page and wiping all of the user's inputs. var userEmail = $("#user-email").val(); $("div.welcomeBox").append("

Welcome "+ username + "

") });

Form Exercise

Create a form in HTML that gets the user's name, email, and phone number.

Display these values to the user in a paragraph in the UI when the user submits the form.

Exercise Gif Trello Logo

In-class practice

  • Create a button that says "Panda Question."
  • When the button is clicked, display a form that asks the user if they like pandas.
  • If the user says "yes", the user should get an alert that says “Me too!”, AND logs a smiley face in the console.
  • If the user says "no", the form should be hidden, AND a sad face should be logged in the console.

Review Video

Watch here

Budget Assignment

Click here for budget/function exercise

Exercise Gif Trello Logo

Reading Assignment

Please read Chapter 7

javascript textbook cover

jQuery Overview

  • JavaScript's Role and the DOM
  • Introducing jQuery and Selectors
  • jQuery Methods
  • jQuery Events
  • Method Chaining
  • jQuery with Forms

THE END

Thank you for your attention!