Upgrade to Pro — share decks privately, control downloads, hide ads and more …

WordCamp Seattle 2017 JavaScript Workshop

Zac Gordon
September 11, 2018

WordCamp Seattle 2017 JavaScript Workshop

Zac Gordon

September 11, 2018
Tweet

More Decks by Zac Gordon

Other Decks in Education

Transcript

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

    View Slide

  2. Go Here to Get Setup
    javascriptforwp.com/wcsea

    View Slide

  3. 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)

    View Slide

  4. 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

    View Slide

  5. JS 101
    Pop Quiz!

    View Slide

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

    View Slide

  7. Question 1/8
    What is a variable?

    View Slide

  8. Question 2/8
    What is an array?

    View Slide

  9. Question 3/8
    What is a function?

    View Slide

  10. Question 4/8
    What is an object?

    View Slide

  11. Question 5/8
    What is a loop?

    View Slide

  12. Question 6/8
    What is a conditional?

    View Slide

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

    View Slide

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

    View Slide

  15. JS 101

    View Slide

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

    View Slide

  17. 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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  21. 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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  25. 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 ] );
    }

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  30. Include JS in HTML




    <br/>console.log( 'JS Running!' );<br/>


    View Slide

  31. Include JS in HTML







    View Slide

  32. 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' );

    View Slide

  33. The DOM
    The Document Object Model

    View Slide

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

    View Slide

  35. BROWSER
    DOM
    HTML
    JavaScript

    View Slide

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

    View Slide

  37. 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

    View Slide

  38. Selecting & Setting
    HTML Elements

    View Slide

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

    View Slide

  40. 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' );

    View Slide

  41. 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' )

    View Slide

  42. 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' );

    View Slide

  43. 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';

    View Slide

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

    View Slide

  45. PRACTICE 1.1
    Getting & Setting Nodes w JS

    View Slide

  46. “Traversing”
    HTML Elements
    Checkout FREE 5 Days of JavaScript

    View Slide

  47. WordCamp Miami 2017
    Creating HTML &
    Adding it to a Page

    View Slide

  48. There Are No
    "HTML Elements”
    in the DOM

    View Slide

  49. In the DOM
    Everything is a Node

    View Slide

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

    View Slide

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

    View Slide

  52. View Slide

  53. 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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  57. 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 );

    View Slide

  58. 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 );

    View Slide

  59. 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 );

    View Slide

  60. 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 );

    View Slide

  61. 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 );

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  66. Practice 1.2 + 1.3

    Creating & Appending Nodes

    View Slide

  67. Events w JavaScript

    View Slide

  68. 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

    View Slide

  69. 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 )

    View Slide

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

    View Slide

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

    View Slide

  72. 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

    View Slide

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

    View Slide

  74. 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

    View Slide

  75. Practice 1.4
    Event Listeners Practice

    View Slide

  76. 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!

    View Slide

  77. The WordPress 

    REST API

    View Slide

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

    View Slide

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

    View Slide

  80. 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

    View Slide

  81. 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

    View Slide

  82. 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

    View Slide

  83. You can also customize
    what you get back.

    View Slide

  84. 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

    View Slide

  85. Practice 2.1

    WP API in the Browser

    View Slide

  86. WordPress API
    w AJAX + JS

    View Slide

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

    View Slide

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

    View Slide

  89. 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

    View Slide

  90. 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

    View Slide

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

    View Slide

  92. 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 );
    }
    }
    });

    View Slide

  93. Practice 2.2 + 2.3

    WP API with Ajax

    View Slide

  94. 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!

    View Slide

  95. JS + API
    Inside of WP

    View Slide

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

    View Slide

  97. 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()

    View Slide

  98. 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()

    View Slide

  99. 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()

    View Slide

  100. Practice 3.1

    Enqueuing JavaScript
    in a Theme

    View Slide

  101. jQuery + WordPress

    View Slide

  102. WordPress comes with
    Several JS Libraries
    Available to Us

    View Slide

  103. 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

    View Slide

  104. The $ in jQuery
    is NOT available
    by default

    View Slide

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

    View Slide

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

    View Slide

  107. Practice 3.2

    Using jQuery for AJAX

    View Slide

  108. 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!

    View Slide

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

    View Slide