JAVASCRIPT SUMMARY

use the arrow keys to navigate; press space for slide overview

JAVASCRIPT SUMMARY

Syntax

Including scripts (1)

  • If your script is the only one running on the page:
    <!DOCTYPE html>
    <html>
    <head>
      <title>How to include scripts</title>
      <meta charset="utf-8" />
    </head>
    <body>
      ...
      <script src="js/my-script.js"></script>
    </body>
    </html>

Including scripts (2)

  • If your page also uses external (vendor) scripts:
    <!DOCTYPE html>
    <html>
    <head>
      <title>How to include scripts</title>
      <meta charset="utf-8" />
    </head>
    <body>
      ...
      <!-- load external libraries first -->
      <script src="vendor/external-script-1.js"></script>
      <script src="vendor/external-script-2.js"></script>
      <!-- load your scripts last -->
      <script src="js/my-script.js"></script>
    </body>
    </html>

Script structure (1)

  • Short version, if your script is the only one running on the page:
    'use strict';
    
    // some functions
    let function1 = function() {
      // ...
    }
    let function2 = function() {
      // ...
    }
    
    // wait for the window to load
    window.addEventListener('load', function() {
      // start your script here
      // ...
    });

Script structure (2)

  • If your page runs other scripts, encapsulate your script in an anonymous function:
    (function() {
      'use strict';
      
      // some functions
      let function1 = function() {
        // ...
      }
      let function2 = function() {
        // ...
      }
    
      // wait for the window to load
      window.addEventListener('load', function() {
        // start your script here
        // ...
      });
    })();

Dialog windows

  • In a browser you can use the standard Javascript dialog windows alert(), confirm() and prompt():
    let name = prompt('Enter your name');
    alert('Hello ' + name);
    let doHighfive = confirm('High five?');
    if (doHighfive) console.log('High five!');
  • only for quick tests; don't use these in production!

Comments

  • PHPDoc-style block comment:
    /**
     * Executed when the module is loaded
     *
     * @param mixed $needle Value we're looking for.
     * @param array $haystack Array of values
     *
     * @return boolean
     */
    let inArray = function(needle, haystack) {
      // ...
    }
  • Inline comment:
    // initializer
    let init = function() {
      // ...
    }

Variables

  • Use let to create any variable:
    let num = 3; // number
    let boo = true; // boolean
    let str = 'hello'; // string; note: you may use single or double quotes
    let fun = function(nm) { console.log('hello' + nm) }; // function
    let arr = [1, 2, 3, 5, 8, 13]; // array
    let rex = /^\d+$/ // regular expression
    let obj = { id: 2, url: 'img/me.jpg', hidden: false } // general object
    let dat = new Date(); // Date object
    

Constants

  • Use const to create a constant:
    // define some constants
    const PI = 3.141592653589793;
    const NUM_LIVES = 3;
    const CAR_MAKES = ['Saab', 'Volvo', 'BMW'];  
    const ME = { name: 'Rogier', age: 48 }              
    

Functions

  • Classic syntax style:
    function myFunction(par1, par2) { 
      // function statements here
      // ...
    } 
  • Newer syntax style:
    let myFunction = function(par1, par2) { 
      // function statements here
      // ...
    }; 
  • we will use the newer syntax in this course

Anonymous functions

  • Are functions without a name; mosty used in event handling, e.g.:
    <input type="button" id="btn1">
    
    document.getElementById('btn1').addEventListener('click', function() {
      console.log(this.id + ' was clicked'); // 'this' refers to element clicked
    });
  • the second parameter of addEventListener is an anonymous function

Objects

  • Objects in Javascript are basically key-value pairs:
    // create an object
    let forrest = {
      firstName: 'Forrest',
      sentence: ,
      says: function() {
        return this.sentence;
      }
    };
    
    // add more properties if you like
    forrest.lastName = 'Gump';
    
    // access properties
    console.log(forrest.firstName);
    console.log(forrest.says());
    
  • to create an object, you don't need a class or constructor

Anonymous objects

  • Are objects without a name; often used to group multiple values in a single parameter:
    // function with only one parameter 'thing'
    let getDescription = function(thing) {
      let str = '';
      str += 'Name: ' + thing.kind + '\n';  
      str += 'Color: ' + thing.color + '\n';  
      str += 'It weighs ' + thing.volume * thing.density + 'kg\n';  
      return str;
    }
    
    // pass an anonymous object and return result
    console.log(getDescription({
      kind: 'lapis lazuli',
      volume: 0.03, // m³
      density: 3000, // kg/m³
      color: 'darkblue'
    }));
    
  • the object has no name; this is called an anonymous object

Iterating an array

  • Use a classic for loop:
    // define an array
    let forrestFriends = ['Bubba', 'Lt. Dan'];
    
    // loop over its values
    for (let i = 0; i < forrestFriends.length; i++) {
      console.log('friend number ' + i + ': ' + forrestFriends[i]);
    }
    
  • If you just need the array values, you can also just use for-of:
    // define an array
    let forrestFriends = ['Bubba', 'Lt. Dan'];
    
    // loop over its values
    for (let friend of forrestFriends) {
      console.log(friend);
    }

Looping over an object

  • To loop over an object's keys, use for-in:
    // define object
    let forrest = {
      firstName: 'Forrest',
      lastName: 'Gump'
    };
    
    // loop over keys
    for (let key in forrest) {
      console.log(key + ' = ' + forrest[key]);
    }

Date, Math, Array

  • Some examples of built-in classes Date, Math and Array (full overview on mozilla.org or w3schools.com):
    // Date example
    let now = new Date(); 
    console.log(now.getFullYear());
    
    // Math example
    console.log(Math.ceil(Math.random() * 10));
    
    // Array example 
    let shakefruits = ['banana', 'orange', 'apple', 'mango'];
    if (shakefruits.includes('orange')) console.log('this shake has orange');
    shakefruits.push('pear'); // add a pear to the array
    console.log(shakefruits);
    

JAVASCRIPT SUMMARY

DOM

How to find elements (1)

  • The elements window, location and document can be used directly (see documentation on W3Schools for window, location and document):
    console.log(window.innerWidth); // window width
    location.href = 'https://www.google.com'; // redirect
    location.reload(); // reload page  
    document.title = 'Javascript — a beginners course'; // set document title
    

How to find elements (2)

  • All other elements can be found with the methods getElementById(), querySelector() and querySelectorAll():
    let button1 = document.getElementbyId('btn1'); // element with id 'btn1'
    let button1 = document.querySelector('#btn1'); // this is identical
    let msg = document.querySelector('#login input'); // get first #login input element
    let images = document.querySelectorAll('.thumbnail'); // get all img elements with class "thumbnail"
  • getElementById(): get by id; returns a single result
  • querySelector(): get by CSS selector; returns a single result
  • querySelectorAll(): get all by CSS selector; returns an array

How to find elements (3)

  • You can chain queries, e.g.:
    // find form, then find password field in that form
    let loginForm = document.getElementbyId('frm1'); 
    let inpPw = loginForm.querySelector('input[type=passwprd]'); // look in loginForm
    
    // find table, then find all cells in that table
    let table1 = document.getElementbyId('my-table'); 
    let cells = table1.querySelectorAll('td'); // look in table1
    
    // this is of course equivalent to:
    let inpPw = document.querySelector('#frm1 input[type=passwprd]'); 
    let cells = document.querySelectorAll('#my-table td'); 
    

getElementById

  • getElementById() gets an element by its id, e.g.:
    <p id="message">message here...</p>
    <button id="btn1">say hello</button>
    document.getElementById('btn1').addEventListener('click', function() {
      document.getElementById('message').innerHTML = 'Hello World';
    });
    ...or a little bit cleaner:
    let button1 = document.getElementById('btn1'); // get button by id
    let msg = document.getElementById('message'); // get paragraph by id
    button1.addEventListener('click', function() {
      msg.innerHTML = 'Hello World';
    });

querySelector

  • querySelector() gets a single element by CSS selector, e.g.:
    <form id="frmLogin">
      <span class="error"></span> 
      <label for="uname">Login: </label><input type="text" id="uname" value="Bob">
      <label for="pw">Password: </label><input type="password" id="pw" value="XYZ">
      <input type="submit" value="login">
    </form>
    let inpName = document.querySelector('#frmLogin input[type=text]');
    let inpPw = document.querySelector('#frmLogin input[type=password]');
    console.log(inpName.value);
    console.log(inpPw.value);
    
  • you can use any selector you know from CSS, so dust off your CSS knowledge!

querySelectorAll (1)

  • querySelectorAll() returns all results in an array:
    <nav>
      <ul>
        <li><a href="">item1</a></li>
        <li><a href="">item2</a></li>
        <li><a href="">item3</a></li>
        <li><a href="">item4</a></li>
      </ul>
    </nav>
    let navlinks = document.querySelectorAll('nav a');
    console.log(navlinks.length); // will display 4

querySelectorAll (2)

  • It returns an array, so you will need to iterate the items:
    <nav>
      <ul>
        <li><a href="">item1</a></li>
        <li><a href="">item2</a></li>
        <li><a href="">item3</a></li>
        <li><a href="">item4</a></li>
      </ul>
    </nav>
    // get even items (this will be item 2 and 4)
    let itemsToHide = document.querySelectorAll('nav li:nth-child(2n)');
    
    // show content of first found
    console.log(itemsToHide[0].innerHTML); // <a href="">item2</a>
    
    // iterate results and do something, e.g. hide them
    for (let item of itemsToHide) {
      item.style.display = 'none'; 
    }

Manipulating elements (1)

  • Some things you can do with almost all elements (see documentation):
    // get it by id
    let el = document.getElementById('myElement');
    
    // change CSS properties
    el.style.backgroundColor = '#cc6'; // note: CSS property is camelCased in Javascript!
    el.style.padding = '20px';
    
    // add/remove CSS classes
    el.classList.add('test'); 
    el.classList.remove('test2'); 
    
    // change the content
    el.innerHTML = 'Hammertime';
    
    // add events
    el.addEventListener('mouseover', function() {
      this.innerHTML = 'Can\'t touch this';
    });

    I am the demo

To run the demo, click 'run' first, then hover over the 'I am the demo' text below

Manipulating elements (2)

  • To know which specific methods and properties per element type exist (e.g. IMG, INPUT, ...), check the documentation. Some examples:
    <form id="demoForm1">
      <label>Yes/no: <input type="checkbox" name="chb1" id="chb1" /></label>;
    </form>
    <img src="img/02_dom/me.jpg" id="img1" width="40" height="40" />
    
    document.getElementById('chb1').checked = true;
    document.getElementById('img1').width = 20;
    this is me

Classlist

  • Set or remove CSS classes with the classList property:
    <button id="btn-view">change view</button>
    <img src="img/02_dom/photo.jpg" id="img-car">
    
    #img-car { opacity: 0.7; transition: all 0.3s; }
    #img-car.zoom { opacity: 1.0; transform: scale(1.3); box-shadow: #888888 5px 5px 10px;' }
    let img = document.querySelector('#img-car');
    let button = document.querySelector('#btn-view');
    button.addEventListener('click', function() {
      if (img.classList.contains('zoom')) img.classList.remove('zoom'); 
      else img.classList.add('zoom');
    });                    
    
    this is me

JAVASCRIPT SUMMARY

Events

Button click example

  • Basic button example:
    <button id="btn1">click me</button>
    // get button
    let button1 = document.getElementById('btn1');
    
    // add click event listener
    button1.addEventListener('click', function() {
      console.log('You clicked me!');
    });

Link click example

  • Basic link example:
    <a href="some-page.html" id="lnk1">go to some page</a>
    // get link
    let link1 = document.getElementById('lnk1');
    
    // add click event listener; note the 'e' (event) parameter
    link1.addEventListener('click', function(e) { 
      e.preventDefault(); // prevent the link of being followed
      console.log('You clicked me!');
    });
  • note that you have to disable the link with e.preventDefault()

Key press example

  • An example for keyboard events:
    <p>type something...</p>
    <input type="text" id="inp1" />
    document.getElementById('inp1').addEventListener('keypress', function(e) {
      console.log('You pressed ' + (e.shiftKey ? 'Shift-' : '')  + e.key + ', code ' + e.keyCode);
    });
  • browser incompatibility may occur; some cross-browser scripts can be found online on quirksmode.org or use a jQuery.

Form checking example

  • Basic form checking example:
    <form id="frm1">
      <label for="pw">Your password: </label><input type="password" id="pw">
      <span class="pw_error"></span> 
      <input type="submit" value="register">
    </form>
    // get form and input
    let form = document.getElementById('frm1');
    let inpPw = form.querySelector('input[type=password]'); 
    let err = form.querySelector('.pw_error');
    
    // handle form submits
    form.addEventListener('submit', function(e) {
      err.innerHTML = ''; // clear errors from previous attempts
      if (inpPw.value.length < 8) {
        err.innerHTML = 'your password is too short'; 
        e.preventDefault(); // prevent submit
      }  
    });
    

Event target

  • If an event is handled by a parent element, you can find out which child was clicked with e.target:
    let table = document.querySelector('#bubbling');
    table.addEventListener('click', function(e) {
      console.log('click was on cell number ' + e.target.innerHTML);
    });
    1 2 3
    4 5 6

JAVASCRIPT SUMMARY

AJAX

Fetch API example

  • AJAX Flickr demo, using the Fetch API:
    <!DOCTYPE html>
    <head>
        <title>Ajax example</title>
        <meta charset="utf-8">
        <style>
            #pics img {
                height: 200px;
                display: block;
                margin-top: 20px;
                margin-right: 20px;
                float: left;
            }
            #search {
                width: 250px;
            }
        </style>
    </head>
    <body>
        <input id="search" type="text" placeholder="enter keyword(s) and press return" />
        <div id="pics"></div>
        <script>
    
            let  pics = document.getElementById('pics');
            let  search = document.getElementById('search');
    
            search.addEventListener('keypress', function(e) {
                if (e.which == 13) {
                    pics.innerHTML = '';
                    makeSearch(this.value);
                }
            });
    
            function onError(error) {
                console.log('Request failed', error)
            }
    
            function onResponse(res) {
                // error
                if (res.status < 200 || res.status >= 300) {
                    console.log('error with status ' + res.status);
                } else {
                    console.log('response ok ' + res.status);
                    return res.json();
                }
            }
    
            function onSuccess(data) {
                // all ok
                for (let  i = 0; i < data.photos.photo.length; i++) {
                    let  img = document.createElement('img');
                    if (data.photos.photo[i].url_m) img.setAttribute('src', data.photos.photo[i].url_m);
                    pics.appendChild(img);
                }
            }
    
            function makeSearch(value) {
                let base = "https://api.flickr.com/services/rest/?";
                let params = "method=flickr.photos.search&extras=url_m&per_page=20&format=json&nojsoncallback=1&safe_search=1";
                params += '&api_key=6ecfcd8d4a3b8a04da6093733db989a2';
                params += '&text=' + encodeURIComponent(value);
                let url = base + params;
                fetch(url)
                  .then(onResponse)
                  .then(onSuccess)
                  .catch(onError);
            }
    
        </script>
    </body>
    </html>
Odisee logo