Slide 1

Slide 1 text

JavaScript for WordPress Zac Gordon @zgordon https://javascriptforwp.com/wcsea

Slide 2

Slide 2 text

Go Here to Get Setup javascriptforwp.com/wcsea

Slide 3

Slide 3 text

Are We Ready?! 1. Slides and Example Files 2. Code Editor (I'm using Atom) 3. JSONView Chrome Extension 4. Local WordPress Install (I'm using Local) 5. FakerPresser Plugin (For dummy content)

Slide 4

Slide 4 text

Workshop Overview 1. JavaScript [ JS 101, DOM, Events ] 2. The WordPress REST API [ Accessing, Arguments ] 3. JS & API in WP Themes [ Enqueuing, WP API ] 4. Homework! Checkout FREE 5 Days of JavaScript

Slide 5

Slide 5 text

JS 101 Pop Quiz!

Slide 6

Slide 6 text

Partner Up! 1 Point for Explaining with Words 1 Point for Coding an Example

Slide 7

Slide 7 text

Question 1/8 What is a variable?

Slide 8

Slide 8 text

Question 2/8 What is an array?

Slide 9

Slide 9 text

Question 3/8 What is a function?

Slide 10

Slide 10 text

Question 4/8 What is an object?

Slide 11

Slide 11 text

Question 5/8 What is a loop?

Slide 12

Slide 12 text

Question 6/8 What is a conditional?

Slide 13

Slide 13 text

Question 7/8 How do you include JavaScript in HTML ?

Slide 14

Slide 14 text

Question 8/8 How do you include JavaScript in a WP Theme?

Slide 15

Slide 15 text

JS 101

Slide 16

Slide 16 text

Variable A container for storing values (in memory) var username = 'zgordon'; let username = 'zgordon'; const siteURL = 'https://site.com';

Slide 17

Slide 17 text

keyword var let const global scope YES NO NO function scope YES YES YES block scope NO YES YES can be reassigned YES YES NO Checkout FREE 5 Days of JavaScript

Slide 18

Slide 18 text

Variable A container for storing values (in memory) var username = 'zgordon', twitter = '@zgordon', website = 'zacgordon.com';

Slide 19

Slide 19 text

Array A collection of values var postIds = [ 1, 2, 3, 5 ]; var usernames = [ 'zgordon', 'admin' ];

Slide 20

Slide 20 text

Array A collection of values (zero indexed) var postIds = [ 1, 2, 3, 5 ]; postIds[ 0 ] // Equals 1 postIds[ postIds.length - 1 ] // Last item

Slide 21

Slide 21 text

Functions Let us write, call and reuse blocks of code function getPosts() { // Function Declaration var posts = apiMagic(); // Will learn.. return posts; } getPosts(); // Function Call getPosts // Function Reference

Slide 22

Slide 22 text

Function Parameters Can pass data into functions function getUser( id = 0 ) { var user = apiMagic( id ); return user; } getUser( 1 );

Slide 23

Slide 23 text

Fat Arrow Functions Let us write, call and reuse blocks of code var posts = getPosts( id => apiMagic( id ) ); Checkout FREE 5 Days of JavaScript

Slide 24

Slide 24 text

Objects Container with properties (values) and methods (functions). var post = { title: 'Hello World!', render: function() { console.log( this.title ); } } post.title; post.render();

Slide 25

Slide 25 text

Loops Let us perform an action on a collection of items. var postIds = [ 1, 7, 14, 34, 88, 117 ]; for ( let i = 0, max = postIds.length; i < max; i++ ) { console.log( 'Post #' + postIds[ i ] ); }

Slide 26

Slide 26 text

For Of Loop Lets us loop through an array var postIds = [ 1, 7, 14 ]; for( let id of postIds ) { console.log( id ); }

Slide 27

Slide 27 text

For Each Method Lets us loop through an array var postIds = [ 1, 7, 14 ]; postIds.forEach( id => { console.log( id ) } );

Slide 28

Slide 28 text

Mapping Mapping is a functional alternative to looping var postIds = [ 1, 7, 14 ]; var newIds = postIds.map( id => { console.log( id ); });

Slide 29

Slide 29 text

Conditional Statements Tests to determine what code to run var loggedIn = true; if ( true === loggedIn ) { console.log( 'Show dashboard' ); } else { console.log( 'Please login' ); }

Slide 30

Slide 30 text

Include JS in HTML console.log( 'JS Running!' );

Slide 31

Slide 31 text

Include JS in HTML

Slide 32

Slide 32 text

Include JS in WP Theme function my_theme_scripts() { wp_enqueue_script( 'main-js', get_template_directory_uri() . '/js/main.js', [ 'jquery', 'wp-api' ], time(), true ); } add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );

Slide 33

Slide 33 text

The DOM The Document Object Model

Slide 34

Slide 34 text

The DOM is an API For HTML (XML & SVG)

Slide 35

Slide 35 text

BROWSER DOM HTML JavaScript

Slide 36

Slide 36 text

Build documents, navigate their structure, and add, modify, or delete elements and content.

Slide 37

Slide 37 text

The DOM API Can • Select HTML elements from a page • Navigate from one element to surrounding elements • Add, edit and delete HTML elements on a page • Build HTML elements and add to a page Checkout FREE 5 Days of JavaScript

Slide 38

Slide 38 text

Selecting & Setting HTML Elements

Slide 39

Slide 39 text

WordCamp Miami 2017 Selecting HTML Elements document.getElementById( 'main' ) document.getElementsByTagName( 'a' ) document.getElementsByClassName( 'post' )

Slide 40

Slide 40 text

WordCamp Miami 2017 Selecting HTML Elements document.querySelector( '.entry-title a' ) document.querySelectorAll( '.entry-title a' ) var h1El = document.querySelector( 'h1' ), aEl = h1El.querySelector( 'a' );

Slide 41

Slide 41 text

WordCamp Miami 2017 Selecting HTML Elements document.getElementById( 'main' ) document.getElementsByTagName( 'a' ) document.getElementsByClassName( 'post' ) document.querySelector( '.entry-title a' ) document.querySelectorAll( '.entry-title a' )

Slide 42

Slide 42 text

WordCamp Miami 2017 Getting Element Attributes el.innerText el.innerHTML el.id el.href el.dataset.custom input.value var el = document.querySelector( 'a' ), input = document.querySelector( 'input' );

Slide 43

Slide 43 text

WordCamp Miami 2017 Setting Element Values var el = document.querySelector( 'a' ); el.href = 'https://javascriptforwp.com'; el.innerText = 'Link'; el.innerHTML = 'Link'; input.value = 'zgordon';

Slide 44

Slide 44 text

WordCamp Miami 2017 Setting CSS Classes var el = document.querySelector( 'a' ); el.classList.add( 'post' ); el.classList.remove( 'post' ); el.classList.toggle( 'post' );

Slide 45

Slide 45 text

PRACTICE 1.1 Getting & Setting Nodes w JS

Slide 46

Slide 46 text

“Traversing” HTML Elements Checkout FREE 5 Days of JavaScript

Slide 47

Slide 47 text

WordCamp Miami 2017 Creating HTML & Adding it to a Page

Slide 48

Slide 48 text

There Are No "HTML Elements” in the DOM

Slide 49

Slide 49 text

In the DOM Everything is a Node

Slide 50

Slide 50 text

Common Node Types • Document [9] • DocumentType [10] • Element [1] • Text [3] • Comments [8] • DocumentFragments [11]

Slide 51

Slide 51 text

Common Node Types • Document [9] • DocumentType [10] • Element [1] • Text [3] • Comments [8] • DocumentFragments [11] Checkout FREE 5 Days of JavaScript

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

10 Doctype Root / HTML 1 Body 1 Head 1 1 Title 3 Title Text 1 Header 1 Paragraph 3 Header Text 3 Text 1 Link 3 3 Link Text 9 Document Window

Slide 54

Slide 54 text

WordCamp Miami 2017 Creating Nodes document.createElement( 'p' ) document.createTextNode( 'Text' )

Slide 55

Slide 55 text

WordCamp Miami 2017 Appending Nodes parent.appendChild( el ); parent.insertBefore( el, elToGoBefore );

Slide 56

Slide 56 text

WordCamp Miami 2017 Appending Text to Element Nodes var p = document.createElement( 'p' ), text = document.createTextNode( 'Text' ); p.appendChild( text );

Slide 57

Slide 57 text

WordCamp Miami 2017 Appending Nodes Example var pEl = document.querySelector( 'p' ), aEl = document.createElement( 'a' ), aText = document.createTextNode( 'Link' ); aEl.appendChild( aText ); aEl.href = 'https://javascriptforwp.com'; pEl.appendChild( aEl );

Slide 58

Slide 58 text

WordCamp Miami 2017 Appending Nodes Example var pEl = document.querySelector( 'p' ), aEl = document.createElement( 'a' ), aText = document.createTextNode( 'Link' ); aEl.appendChild( aText ); aEl.href = 'https://javascriptforwp.com'; pEl.appendChild( aEl );

Slide 59

Slide 59 text

WordCamp Miami 2017 Appending Nodes Example var pEl = document.querySelector( 'p' ), aEl = document.createElement( 'a' ), aText = document.createTextNode( 'Link' ); aEl.appendChild( aText ); aEl.href = 'https://javascriptforwp.com'; pEl.appendChild( aEl );

Slide 60

Slide 60 text

WordCamp Miami 2017 Appending Nodes Example var pEl = document.querySelector( 'p' ), aEl = document.createElement( 'a' ), aText = document.createTextNode( 'Link' ); aEl.appendChild( aText ); aEl.href = 'https://javascriptforwp.com'; pEl.appendChild( aEl );

Slide 61

Slide 61 text

WordCamp Miami 2017 Appending Nodes Example var pEl = document.querySelector( 'p' ), aEl = document.createElement( 'a' ), aText = document.createTextNode( 'Link' ); aEl.appendChild( aText ); aEl.href = 'https://javascriptforwp.com'; pEl.appendChild( aEl );

Slide 62

Slide 62 text

WordCamp Miami 2017 “Hacker Style” Appending Nodes var pEl = document.querySelector( 'p' ), markup = ''; markup += ''; markup += 'Link Text'; markup += ''; pEl.innerHTML = markup;

Slide 63

Slide 63 text

WordCamp Miami 2017 “Hacker Style” Appending Nodes var pEl = document.querySelector( 'p' ), markup = ''; markup += ''; markup += 'Link Text'; markup += ''; pEl.innerHTML = markup;

Slide 64

Slide 64 text

WordCamp Miami 2017 “Hacker Style” Appending Nodes var pEl = document.querySelector( 'p' ), markup = ''; markup += ''; markup += 'Link Text'; markup += ''; pEl.innerHTML = markup;

Slide 65

Slide 65 text

WordCamp Miami 2017 “Hacker Style” Appending Nodes var pEl = document.querySelector( 'p' ), markup = ''; markup += ''; markup += 'Link Text'; markup += ''; pEl.innerHTML = markup;

Slide 66

Slide 66 text

Practice 1.2 + 1.3
 Creating & Appending Nodes

Slide 67

Slide 67 text

Events w JavaScript

Slide 68

Slide 68 text

WordCamp Miami 2017 Types of Events • Mouse events • Keyboard events • Form events • Media events • Drag and Drop events • Window events • Many more…. Checkout FREE 5 Days of JavaScript

Slide 69

Slide 69 text

WordCamp Miami 2017 Hooking into Events w JavaScript 1. Inline in HTML 2. Global 1 Off 3. Listeners Best Alert a.onclick = sayHi a.addEventListener( 'click', sayHi, false )

Slide 70

Slide 70 text

WordCamp Miami 2017 Event Listeners var linkEl = document.querySelector( 'a' ); linkEl.addEventListener( 'click', displayClickInfo ); function displayClickInfo() { alert( 'Link clicked!' ); }

Slide 71

Slide 71 text

WordCamp Miami 2017 The Event Object var linkEl = document.querySelector( 'a' ); linkEl.addEventListener( 'click', displayClickInfo ); function displayClickInfo( event ) { alert( event ); }

Slide 72

Slide 72 text

WordCamp Miami 2017 The Event Object link.addEventListener( 'click', showEvent ); function showEvent( event ) { console.log( event ); console.log( event.type ); console.log( event.target ); console.log( event.preventDefault() ); } Checkout FREE 5 Days of JavaScript

Slide 73

Slide 73 text

WordCamp Miami 2017 Removing Event Listeners var el = document.querySelector( 'a' ); el.addEventListener( 'click', sayHi ); el.removeEventListener( 'click', sayHi );

Slide 74

Slide 74 text

WordCamp Miami 2017 Removing Event Listeners var el = document.querySelector( 'a' ); el.addEventListener( 'click', sayHi ); el.remove(); // Listener still exists el = null; // Listener does NOT exist

Slide 75

Slide 75 text

Practice 1.4 Event Listeners Practice

Slide 76

Slide 76 text

Workshop Overview 1. JavaScript [ JS 101, DOM, Events ] 2. The WordPress REST API [ Accessing, Arguments ] 3. JavaScript & WP API in Themes [ Enqueuing, jQuery, API ] 4. Homework!

Slide 77

Slide 77 text

The WordPress 
 REST API

Slide 78

Slide 78 text

The WP REST API Allows us to get, save, edit, and remove content from WordPress using JSON & JavaScript.

Slide 79

Slide 79 text

The WP REST API Allows us to get, save, edit, and remove content from WordPress using JavaScript.

Slide 80

Slide 80 text

The WordPress REST API /wp-json/wp/v2/posts /wp-json/wp/v2/revisions /wp-json/wp/v2/categories /wp-json/wp/v2/tags /wp-json/wp/v2/pages /wp-json/wp/v2/comments /wp-json/wp/v2/taxonomies /wp-json/wp/v2/media /wp-json/wp/v2/users /wp-json/wp/v2/types /wp-json/wp/v2/statuses /wp-json/wp/v2/settings /wp-json/custom/v1/something /wp-json/another/v3/else

Slide 81

Slide 81 text

The WordPress REST API To access all of the posts for your site: https://yoursite.com/wp-json/wp/v2/posts To access a post with an ID of “1” for your site: https://yoursite.com/wp-json/wp/v2/posts/1

Slide 82

Slide 82 text

The WordPress REST API To access all of the pages for your site: https://yoursite.com/wp-json/wp/v2/pages To access a page with an ID of “5” for your site: https://yoursite.com/wp-json/wp/v2/pages/5

Slide 83

Slide 83 text

You can also customize what you get back.

Slide 84

Slide 84 text

The WordPress REST API https://yoursite.com/wp-json/wp/v2/posts ? per_page=10
 &_embed
 &search=hello%20world
 &orderby=title
 &order=asc https://developer.wordpress.org/rest-api/reference/posts/#arguments

Slide 85

Slide 85 text

Practice 2.1
 WP API in the Browser

Slide 86

Slide 86 text

WordPress API w AJAX + JS

Slide 87

Slide 87 text

AJAX Allows us to get content from a server or send content to a server using JavaScript.

Slide 88

Slide 88 text

AJAX w WP API Allows us to get, save, edit and delete WordPress content using JavaScript and JSON.

Slide 89

Slide 89 text

Ways to Make JS AJAX Calls • XMLHttpRequests() [Web API] • fetch() [Web API] • jQuery [Library] • Axios [Library] • WP API Specific [In Core, Decoupled] Checkout FREE 5 Days of JavaScript

Slide 90

Slide 90 text

WP API AJAX Behind the Scenes 1. Define the URL to use 2. Make a request to the URL 3. Get JSON back from 4. Parse JSON into Native JavaScript 5. Use Native JavaScript

Slide 91

Slide 91 text

Pseudo AJAX var postsJSON = fetch('https://wp.dev/wp-json/wp/v2/posts'), posts = JSON.parse( postsJSON ); for( let post of posts ) { renderPost( post ); }

Slide 92

Slide 92 text

AJAX with jQuery $.ajax({ type: 'get', url: 'https://site.com/wp-json/wp/v2/posts/', data: { per_page: 3, order: 'asc' }, success: function( response ) { for( let post of response ) { renderPost( post ); } } });

Slide 93

Slide 93 text

Practice 2.2 + 2.3
 WP API with Ajax

Slide 94

Slide 94 text

Workshop Overview 1. JavaScript [ JS 101, DOM, Events ] 2. The WordPress REST API [ Accessing, Arguments ] 3. JavaScript & WP API in Themes [ Enqueuing, jQuery, API ] 4. Homework!

Slide 95

Slide 95 text

JS + API Inside of WP

Slide 96

Slide 96 text

Enqueuing JavaScript The process of loading JavaScript into a theme or the admin area via PHP functions. wp_enqueue_script() wp_localize_script()

Slide 97

Slide 97 text

function my_theme_scripts() { wp_enqueue_script( 'main-js', // Unique name get_template_directory_uri() . '/js/main.js', // Path [ 'jquery', 'wp-api' ], // Dependencies time(), // Version true ); // Include in footer (v header) } add_action('wp_enqueue_scripts', 'my_theme_scripts', 999); wp_enqueue_script()

Slide 98

Slide 98 text

function my_theme_scripts() { wp_enqueue_script( 'main-js', ... ); wp_localize_script( 'main-js', // File to localize 'myGlobalVars', // Name of localize object [ // Array of properties 'siteUrl' => esc_url( home_url() ), 'siteName'=> get_bloginfo( 'name' ) ] ); } add_action('wp_enqueue_scripts', 'my_theme_scripts', 999); wp_localize_script()

Slide 99

Slide 99 text

functions.php function my_theme_scripts() { wp_enqueue_script( 'main-js', ... ); wp_localize_script( 'main-js', 'myGlobalVars', ... ); } add_action('wp_enqueue_scripts', 'my_theme_scripts', 999); main.js console.log( myGlobalVars.siteUrl ); wp_localize_script()

Slide 100

Slide 100 text

Practice 3.1
 Enqueuing JavaScript in a Theme

Slide 101

Slide 101 text

jQuery + WordPress

Slide 102

Slide 102 text

WordPress comes with Several JS Libraries Available to Us

Slide 103

Slide 103 text

function my_theme_scripts() { wp_enqueue_script( 'main-js', // Unique name get_template_directory_uri() . '/js/main.js', // Path [ 'jquery' ], // Dependencies time(), // Version true ); // Include in footer (v header) } add_action('wp_enqueue_scripts', 'my_theme_scripts', 999); jQuery Dependency

Slide 104

Slide 104 text

The $ in jQuery is NOT available by default

Slide 105

Slide 105 text

jQuery( '.this-works' ).show();

Slide 106

Slide 106 text

(function( $ ) { $('.this-works').show(); })( jQuery ); Immediately Evoked Function Expression (IEFE)

Slide 107

Slide 107 text

Practice 3.2
 Using jQuery for AJAX

Slide 108

Slide 108 text

Workshop Overview 1. JavaScript [ JS 101, DOM, Events ] 2. The WordPress REST API [ Accessing, Arguments ] 3. JavaScript & WP API in Themes [ Enqueuing, jQuery, API ] 4. Homework!

Slide 109

Slide 109 text

WordCamp Miami 2017 Learn JavaScript More Deeply with Me! javascriptforwp.com/wcsea