JavaScript Reference



This is my simple JavaScript reference.

Table of Contents

  1. Arrays
  2. The DOM Structure
    1. Locating Nodes
    2. Creating, Deleting, and Cloning Nodes
  3. Mouse Events
  4. Event Listeners
  5. Timers

Arrays

creating, length, push, unshift, pop, shift, join, and concat

// creating arrays
var array = ['Monday', 10, false]; // elements can be of any data type
var array2 = new Array(5); // array of 5 empty elements

// length - checking length of an array
console.log(array2.length); // -> 5

// push() and unshift() - adding to the end / front
array.push('Cake'); // -> Monday, 10, false, Cake
array.unshift(100); // -> 100, Monday, 10, false, Cake

// pop() and shift() - removing the last / first element
console.log(array.pop()); // -> Cake
console.log(array.shift()); // -> 100

// join() - joins elements of an array (comma is the default separator)
console.log(array.join());     // -> Monday,10,false
console.log(array.join('; ')); // -> Monday; 10; false

// concat() - concatenating arrays - does not change the array
var result = array.concat('Ice Cream', true, 5)
console.log(array);  // -> Monday, 10, false
console.log(result); // -> Monday, 10, false, Ice Cream, true, 5

sort, reverse, indexOf, lastIndexOf

var names = ['Jake', 'Roland', 'Eddie', 'Susan'];

// sort() - sorting -> names is now Eddie, Jake, Roland, Susan
console.log(names.sort());

// reverse() - reversing an array -> names is now Susan, Roland, Jake, Eddie
console.log(names.reverse());

// indexOf(element) - searching for an element
console.log(names.indexOf('Jake')); // -> 2
console.log(names.indexOf('JAKE')); // -> -1

// indexOf(element, starting_position)
console.log(names.indexOf('Jake', 3)); // -> -1

// lastIndexOf(element)
console.log(names.lastIndexOf('Jake')); // -> 2

slice and splice

// slice(start_position [, end_position - exclusive]) - extracting part of an array
// --> does NOT change the array
var names = ['Susan', 'Roland', 'Jake', 'Eddie'];
var sliced = names.slice(1);
console.log(sliced); // -> Roland, Jake, Eddie
console.log(names); // -> Susan, Roland, Jake, Eddie

sliced = names.slice(1, 3);
console.log(sliced); // -> Roland, Jake

// splice(startPosition, numberOfElements)
// removes elements from an array and returns them
var desserts = ['Ice Cream', 'Cookie', 'Cake'];
var spliced = desserts.splice(0, 2);

console.log(desserts); // -> Cake
console.log(spliced); // -> Ice Cream, Cookie

// splice can also add elements
spliced = desserts.splice(1, 0, 'Fruit');
spliced = desserts.splice(1, 0, 'Ice Cream', 'Cookie');

console.log(desserts); // -> Cake, Ice Cream, Cookie, Fruit
console.log(spliced); // -> []

// and replace elements - replace Cookie and Fruit with Cheese Cake
spliced = desserts.splice(2, 2, 'Cheese Cake');

console.log(desserts); // -> Cake, Ice Cream, Cheese Cake
console.log(spliced); // -> Cookie, Fruit

forEach and map

// forEach - iterating over an array using forEach
// -> takes a function with three arguments (element, index, array) as the parameter
// -> the function taken as the parameter can change the array
var desserts = ['Ice Cream', 'Cookie', 'Cake'];

desserts.forEach(function(element, index, array) {
  console.log('array[' + index + '] = ' + element);
  array[index] = 'Mhm - ' + element;
});

console.log(desserts); // Mhm - Ice Cream, Mhm - Cookie, Mhm - Cake

// ----------------------------------------

// map - applies a function to each element - does not change the original array
// -> takes a function with two arguments (array, some_function) as the parameter
var desserts = ['Ice Cream', 'Cookie', 'Cake'];

var result = desserts.map(function(element) {
  return "I want " + element;
});

console.log(desserts); // Ice Cream, Cookie, Cake
console.log(result); // I want Ice Cream, I want Cookie, I want Cake

The DOM Structure

Locating Nodes

Three ways to search for an element in the DOM structure:

  • by specifying the exact path to an element,
  • by using getElementsByTagName to find all elements of a given tag type and accessing one of them,
  • by using getElementById to find an element by its id.
<html>
<head>
  <script>
    // Three ways to search for an element in the DOM structure

    // using exact path to an element
    function find_by_path() {
      //                   /- head
      // document <- html <-  #text (new line)
      //                   \- body <-  #text (new line)
      //                            \- p
      //                            |- #text (new line)
      //                            |- form
      //                            |- #text (new line)
      //
      //       html <------- body <------  p
      document.childNodes[0].childNodes[2].childNodes[1].style.color = "red";
    }

    // by finding all elements of a given tag type and accessing one of them
    function find_by_tag_type() {
      document.getElementsByTagName("p")[0].style.color = "green";
    }

    // by finding an element by its id
    function find_by_id() {
      document.getElementById("my_paragraph").style.color = "blue";
    }
  </script>
</head>
<body>
  <p id="my_paragraph">Test paragraph</p>
  <form>
    <input type="button" onclick="find_by_path()" value="Find by path"/>
    <input type="button" onclick="find_by_tag_type()" value="Find by tag type"/>
    <input type="button" onclick="find_by_id()" value="Find by id"/>
  </form>
</body>
</html>

Creating, Deleting, and Cloning Nodes

<html>
<head>
  <script>
    // document.createElement
    // document.createTextNode
    // node.appendChild
    // node.insertBefore - inserts an element before another element
    // node.firstChild
    function add_paragraph() {
      var p = document.createElement("p");
      p.appendChild(document.createTextNode("Test. "));

      var div = document.getElementById("test_div");
      div.insertBefore(p, div.firstChild);
    }

    // node.parentNode
    // node.removeChild
    function delete_first_paragraph() {
      var p = document.getElementsByTagName("p")[0];
      if (p)
        p.parentNode.removeChild(p);
    }

    function delete_all_paragraphs() {
      var div = document.getElementById("test_div");

      while (div.firstChild)
        div.removeChild(div.firstChild);
    }

    // cloneNode() - clone a single element
    function clone_button() {
      var new_button = document.getElementById("my_button").cloneNode();

      // insert the cloned button before the original one
      document.getElementsByTagName("form")[0].appendChild(new_button);
    }

    // cloneNode(true) - clone a whole branch
    function clone_test_div() {
      var new_div = document.getElementById("test_div").cloneNode(true);

      document.getElementsByTagName("body")[0].appendChild(new_div);
    }
  </script>
</head>
<body>
  <form>
    <input type="button" onclick="add_paragraph()" value="Add a paragraph"/>
    <input type="button" onclick="delete_first_paragraph()" value="Delete the first paragraph"/>
    <input type="button" onclick="delete_all_paragraphs()" value="Delete all paragraphs"/>
    <input id="my_button" type="button" onclick="clone_button()" value="Clone this button"/>
    <input type="button" onclick="clone_test_div()" value="Clone whole div"/>
  </form>
  <div id="test_div"></div>
</body>
</html>

Mouse Events

Simple example of handling mouse events to move a div:

<html>
<head>
  <script>
    var mouse_down = false;
    var old_mouse_x;
    var old_mouse_y;

    function handle_mouse_move(e) {
      if (mouse_down) {
        var div = document.getElementById("my_div");

        div.style.left = (Number(div.style.left.replace("px", "")) + e.clientX - old_mouse_x) + "px";
        div.style.top = (Number(div.style.top.replace("px", "")) + e.clientY - old_mouse_y) + "px";

        old_mouse_x = e.clientX;
        old_mouse_y = e.clientY;
      }
    }

    function handle_mouse_down(e) {
      mouse_down = true;
      old_mouse_x = e.clientX;
      old_mouse_y = e.clientY;
    }

    function handle_mouse_up() {
      mouse_down = false;
    }
  </script>
</head>
<body>
  <div id="main_div"
       onmousemove="handle_mouse_move(event)"
       style="background-color: yellow; width: 300px; height: 300px;">
    <div id="my_div"
         onmousedown="handle_mouse_down(event)"
         onmouseup="handle_mouse_up()"
         style="background-color: blue; width: 20px; height: 20px; position: relative; left: 30px; top: 30px;"></div>
  </div>
</body>
</html>

Event Listeners

<html>
<head>
  <script>
    function show_message() {
      alert("Hello");
    }

    function addListener() {
      document.getElementsByTagName("p")[0].addEventListener("click", show_message);
    }

    function removeListener() {
      document.getElementsByTagName("p")[0].removeEventListener("click", show_message);
    }
  </script>
</head>
<body>
  <form>
    <input type="button" onclick="addListener()" value="Add listener"/>
    <input type="button" onclick="removeListener()" value="Remove listener"/>
  </form>
  <p>Click me after adding a listener.</p>
</body>
</html>

Timers

<html>
<head>
</head>
<body>
  <script>
    // will show message once
    var timer = setTimeout(function() { alert("Hello World!"); }, 2000);
    // clearTimeout(timer) can be used to stop the timer

    // will add an element every second
    var interval = setInterval(
      function() { document.getElementsByTagName("body")[0].appendChild(
                     document.createTextNode("Test."));
      }, 1000);

    // clearInterval(interval) can be used to stop an interval
  </script>
</body>
</html>

Leave a Reply

Your email address will not be published.


9 × = nine

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>