Skip to main content

Ivan Teoh

Something personal yet public

I am working on converting my personal site from WordPress to static website using Nikola, static website and blog generator in Python.

Meanwhile, you still can visit old site that still using WordPress until the completion of conversion.

Updates: 18 Jul 2012

Conversion completed. Now, the old site is closed.

I just finished cooking bubur cha-cha. Again, it is not as nice as the one in Penang. It is one of my favorite dish during Chinese New Year. It is usually served during the last day (15th) of Chinese New Year for Hokkiens. This version was just sweet potato, sago and black-eyed pea. It is too watery. I will put less water and coconut milk next time.

References

I just updated my Mac with OS X Lion. After playing a while, I realise I can't find Macintosh HD. It no longer at left-side bar in Finder. I need it. So I came out with a solution as below.

  • Right click on Application and click Open Enclosing Folder. It will open Macintosh HD folder in new window.
  • Drag the top center icon, disc, to the left-side bar in Finder under Favorites.

Now, I have Macintosh HD folder as favorited folder in Finder.

Updates: 22 Jul 2011

Another solution is open Finder Preferences, select / check Hard disks on Sidebar tab under Devices section.

First Protovis, now D3. Both are works from Mike Bostock. Both are data visualization JavaScript libraries.

This tutorial we’re going to create a basic dot graph with scalable y-axis. It is adapted from one of the examples in D3, dot.html.

Step 1: Default html

First of all, we create a default html that contains a div for input button and another for the graph. We also link the d3 JavaScript library. The rest of tutorial will be concentrate of JavaScript code that will be written after the comment, "Scale graph code here."

176-step1.html (Source)

<!DOCTYPE html>
<html>
<head>
    <title>Scale Graph</title>
</head>
<body>
    <div id="demoContainer">
        <div id="option">
            <input name="updateButton" type="button" value="Update"/>
        </div>
        <div id="mainGraph">
        </div>
    </div>
    <script type="text/javascript"
      src="http://mbostock.github.com/d3/d3.js?1.27.1"></script>
    <script type="text/javascript">
    <!-- Scale graph code here. -->
    </script>
</body>
</html>

Step 2: Random data

We need to generate some random data using Math.random(). We create randomData function for returning a list of ten x and y values. For example, [{“x”: 0, “y”: 0.3}, {“x”: 0.1, “y”: 0.4}, ...]

176-step2.js (Source)

function randomData() {
    return d3.range(10).map(function(i) {
        return {x: i / 9, y: Math.random()};
    });
}

Step 3: Maximum value of y-axis

For this tutorial, only y axis values are random. We need to get maximum value of the y axis using d3.max, in order to scale the y axis based on the maximum value of the data.

176-step3.js (Source)

var data = randomData();
var newMaxY = d3.max(data, function(d) {return d.y;});

Step 4: Ceil value

Sometime, the maximum value doesn’t suitable for domain range in scale axis. For example, 0.33333. Mike suggested a method to increase the size of domain to next highest rounded value.

176-step4.js (Source)

function reDomain(maxValue) {
    var dy = Math.pow(10, Math.round(Math.log(maxValue) / Math.log(10)) - 1);
    return Math.ceil(maxValue / dy) * dy;
}

var newCeilY = reDomain(newMaxY);

Step 5: SVG container

Now, we determine the size of the graph, which are w and h for width and height. We need a svg container for the graph. We will append it inside #mainGraph div with width and height attributes. This is optional, which offset the graph with modify coordinate using translate in transform in a group. The <g> element is used to group SVG shapes together. For example, <g transform="translate(50,50)">` will translate coordinate **["x": 50, "y": 50] as zero in the that group.

176-step5.js (Source)

var w = 450,
    h = 450,
    p = 50,
    x = d3.scale.linear().domain([0, 1]).range([0, w]),
    y = d3.scale.linear().domain([0, newCeilY]).range([h, 0]);

var chart = d3.select("#mainGraph")
    .append("svg:svg")
    .attr("width", w + p * 2)
    .attr("height", h + p * 2);

var vis = chart.append("svg:g")
    .attr("transform", "translate(" + p + "," + p + ")");

Step 6: Rulers

Now, we add both x and y axises line grids and labels. We also notice that d3 supports css style. We make #ccc colour stroke style for both x and y line grids.

176-step6.js (Source)

var xrule = vis.selectAll("g.x")
    .data(x.ticks(10))
    .enter().append("svg:g")
    .attr("class", "x");

xrule.append("svg:line")
    .style("stroke", "#ccc")
    .style("shape-rendering", "crispEdges")
    .attr("x1", x)
    .attr("x2", x)
    .attr("y1", 0)
    .attr("y2", h);

xrule.append("svg:text")
    .attr("x", x)
    .attr("y", h + 3)
    .attr("dy", ".71em")
    .attr("text-anchor", "middle")
    .text(x.tickFormat(10));

var yrule = vis.selectAll("g.y")
    .data(y.ticks(10))
    .enter().append("svg:g")
    .attr("class", "y");

yrule.append("svg:line")
    .attr("class", "yLine")
    .style("stroke", "#ccc")
    .style("shape-rendering", "crispEdges")
    .attr("x1", 0)
    .attr("x2", w)
    .attr("y1", y)
    .attr("y2", y);

yrule.append("svg:text")
    .attr("class", "yText")
    .attr("x", -3)
    .attr("y", y)
    .attr("dy", ".35em")
    .attr("text-anchor", "end")
    .text(y.tickFormat(10));

Step 7: Dots

This is the last step for the dots graph. All the dots are paths. What kind of symbols of the path is determined by d attribute. We also add title attribute in the path, so that when mouse is hovering the dots, tool tip is shown. Color of the dots fill is changed too. After you completed this steps, we will see a basic dot graph.

176-step7.js (Source)

var node = vis.selectAll("path.dot")
        .data(data)
        .enter().append("svg:path")
        .attr("class", "dot")
        .style("fill", "white")
        .style("stroke-width", "1.5px")
        .attr("stroke", "#9acd32")
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," +
          y(d.y) + ")"; })
        .attr("d", d3.svg.symbol())
        .on("mouseover", function(d,i) {
            d3.select(this).transition().duration(300).style("fill","#00ffff");
        })
        .on("mouseout", function(d,i) {
            d3.select(this).transition().duration(300).style("fill","white");
        });

node.append("svg:title")
    .attr("class", "dotTitle")
    .text(function(d) {
      return "X: " + d.x.toFixed(3) + ", Y: " + d.y.toFixed(3);
    });

Step 8: Update button

This step is explaining what will happen after update button is clicked. Before that, we need to add onclick attribute in button type input with the update function name. For example, <input name="updateButton" type="button" value="Update" onclick="updateData()"/>. In the update function, we will get a new data list from randomData function. Then get the maximum ceil value, which is similar in initData function. Since, we are only want to rescale the y axis, we will select g.y. Make sure to select their parent, #mainGraph svg g, first before selecting them, in order to append the extra line grid in the right parent. For updating the line grids and labels, we are going to use update, enter and exit selections. Since we are append new line grid and label, we need to set all the attributes that are needed. On the other hand, we only update attributes that need to be changes in update and exit selections. Lastly, don't forget about updating the dots data too.

176-step8.js (Source)

function updateData() {
    var data = randomData();
    var newMaxY = d3.max(data, function(d) {return d.y;});
    var newCeilY = reDomain(newMaxY);

    var w = 450,
        h = 450,
        x = d3.scale.linear().domain([0, 1]).range([0, w]),
        y = d3.scale.linear().domain([0, newCeilY]).range([h, 0]);

    var vis = d3.select("#mainGraph svg g");

    var yrule = vis.selectAll("g.y")
        .data(y.ticks(10));

    // yRule Enter
    var newrule = yrule.enter().append("svg:g")
        .attr("class", "y");

    newrule.append("svg:line")
        .attr("class", "yLine")
        .style("stroke", "#ccc")
        .style("shape-rendering", "crispEdges")
        .attr("x1", 0)
        .attr("x2", w)
        .attr("y1", 0)
        .attr("y2", 0)
        .transition()
        .duration(2000)
        .attr("y1", y)
        .attr("y2", y);

    newrule.append("svg:text")
        .attr("class", "yText")
        .attr("x", -3)
        .attr("dy", ".35em")
        .attr("text-anchor", "end")
        .attr("y", 0)
        .transition()
        .duration(2000)
        .attr("y", y)
        .text(y.tickFormat(10));

    // yLine Update
    yrule.select("line.yLine")
        .transition()
        .duration(2000)
        .attr("y1", y)
        .attr("y2", y);

    // yText Update
    yrule.select("text.yText")
        .transition()
        .duration(2000)
        .attr("y", y)
        .text(y.tickFormat(10));

    // yrule Remove
    var oldrule = yrule.exit();

    oldrule.select("line.yLine")
        .transition()
        .duration(2000)
        .attr("y1", 0)
        .attr("y2", 0)
        .remove();


    oldrule.select("text.yText")
        .transition()
        .duration(2000)
        .attr("y", 0)
        .remove();

    oldrule.transition()
        .duration(2000).remove();

    // Dots
    var node = vis.selectAll("path.dot")
        .data(data)
        .transition()
        .duration(2000)
        .attr("transform", function(d) {
          return "translate(" + x(d.x) + "," + y(d.y) + ")";
        });

    node.select("title.dotTitle")
        .text(function(d) {
          return "X: " + d.x.toFixed(3) + ", Y: " + d.y.toFixed(3);
        });

}

Step 9: Summary

This tutorial is written based on my personal understanding on D3. I am still learning. Any feedback are welcome.

176-step9.html (Source)

<!DOCTYPE html>
<html>
<head>
    <title>Scale Graph</title>
</head>
<body>
    <div id="demoContainer">
        <div id="option">
            <input name="updateButton" type="button" value="Update"
              onclick="updateData()" />
        </div>
        <div id="mainGraph">
        </div>
    </div>
    <script type="text/javascript"
      src="http://mbostock.github.com/d3/d3.js?1.27.1"></script>
    <script type="text/javascript">
    /* Global variables */

    /* Definition code */
    function randomData() {
        return d3.range(10).map(function(i) {
            return {x: i / 9, y: Math.random()};
        });
    }

    function reDomain(maxValue) {
        var dy = Math.pow(10, Math.round(Math.log(maxValue) /
          Math.log(10)) - 1);
        return Math.ceil(maxValue / dy) * dy;
    }

    function updateData() {
        var data = randomData();
        var newMaxY = d3.max(data, function(d) {return d.y;});
        var newCeilY = reDomain(newMaxY);

        var w = 450,
            h = 450,
            x = d3.scale.linear().domain([0, 1]).range([0, w]),
            y = d3.scale.linear().domain([0, newCeilY]).range([h, 0]);

        var vis = d3.select("#mainGraph svg g");

        var yrule = vis.selectAll("g.y")
            .data(y.ticks(10));

        // yRule Enter
        var newrule = yrule.enter().append("svg:g")
            .attr("class", "y");

        newrule.append("svg:line")
            .attr("class", "yLine")
            .style("stroke", "#ccc")
            .style("shape-rendering", "crispEdges")
            .attr("x1", 0)
            .attr("x2", w)
            .attr("y1", 0)
            .attr("y2", 0)
            .transition()
            .duration(2000)
            .attr("y1", y)
            .attr("y2", y);

        newrule.append("svg:text")
            .attr("class", "yText")
            .attr("x", -3)
            .attr("dy", ".35em")
            .attr("text-anchor", "end")
            .attr("y", 0)
            .transition()
            .duration(2000)
            .attr("y", y)
            .text(y.tickFormat(10));

        // yLine Update
        yrule.select("line.yLine")
            .transition()
            .duration(2000)
            .attr("y1", y)
            .attr("y2", y);

        // yText Update
        yrule.select("text.yText")
            .transition()
            .duration(2000)
            .attr("y", y)
            .text(y.tickFormat(10));

        // yrule Remove
        var oldrule = yrule.exit();

        oldrule.select("line.yLine")
            .transition()
            .duration(2000)
            .attr("y1", 0)
            .attr("y2", 0)
            .remove();


        oldrule.select("text.yText")
            .transition()
            .duration(2000)
            .attr("y", 0)
            .remove();

        oldrule.transition()
            .duration(2000).remove();

        // Dots
        var node = vis.selectAll("path.dot")
            .data(data)
            .transition()
            .duration(2000)
            .attr("transform", function(d) {
              return "translate(" + x(d.x) + "," + y(d.y) + ")";
            });

        node.select("title.dotTitle")
            .text(function(d) {
              return "X: " + d.x.toFixed(3) + ", Y: " + d.y.toFixed(3);
            });

    }

    var initData = function() {
        var data = randomData();
        var newMaxY = d3.max(data, function(d) {return d.y;});
        var newCeilY = reDomain(newMaxY);

        var w = 450,
            h = 450,
            p = 50,
            x = d3.scale.linear().domain([0, 1]).range([0, w]),
            y = d3.scale.linear().domain([0, newCeilY]).range([h, 0]);

        var chart = d3.select("#mainGraph")
            .append("svg:svg")
            .attr("width", w + p * 2)
            .attr("height", h + p * 2);

        var vis = chart.append("svg:g")
            .attr("transform", "translate(" + p + "," + p + ")");

        var xrule = vis.selectAll("g.x")
            .data(x.ticks(10))
            .enter().append("svg:g")
            .attr("class", "x");

        xrule.append("svg:line")
            .style("stroke", "#ccc")
            .style("shape-rendering", "crispEdges")
            .attr("x1", x)
            .attr("x2", x)
            .attr("y1", 0)
            .attr("y2", h);

        xrule.append("svg:text")
            .attr("x", x)
            .attr("y", h + 3)
            .attr("dy", ".71em")
            .attr("text-anchor", "middle")
            .text(x.tickFormat(10));

        var yrule = vis.selectAll("g.y")
            .data(y.ticks(10))
            .enter().append("svg:g")
            .attr("class", "y");

        yrule.append("svg:line")
            .attr("class", "yLine")
            .style("stroke", "#ccc")
            .style("shape-rendering", "crispEdges")
            .attr("x1", 0)
            .attr("x2", w)
            .attr("y1", y)
            .attr("y2", y);

        yrule.append("svg:text")
            .attr("class", "yText")
            .attr("x", -3)
            .attr("y", y)
            .attr("dy", ".35em")
            .attr("text-anchor", "end")
            .text(y.tickFormat(10));

        var node = vis.selectAll("path.dot")
                .data(data)
                .enter().append("svg:path")
                .attr("class", "dot")
                .style("fill", "white")
                .style("stroke-width", "1.5px")
                .attr("stroke", "#9acd32")
                .attr("transform", function(d) {
                  return "translate(" + x(d.x) + "," + y(d.y) + ")";
                })
                .attr("d", d3.svg.symbol())
                .on("mouseover", function(d,i) {
                    d3.select(this).transition().duration(300).style(
                      "fill","#00ffff"); })
                .on("mouseout", function(d,i) {
                    d3.select(this).transition().duration(300).style(
                      "fill","white"); });

        node.append("svg:title")
            .attr("class", "dotTitle")
            .text(function(d) {
              return "X: " + d.x.toFixed(3) + ", Y: " + d.y.toFixed(3);
            });
    }

    /* UI Events */
    /* Execution code */
    initData();
    </script>
</body>
</html>

Updates: 15 Jul 2011

Ricardo mentions transitioning scales example, Date Ticks by mbostock.

On week 5 track 2, we continue study chapter 12 and 13 on Eloquent Javascript. Both chapters are related to document-object model and browser events.

Reflection

  1. What factors make accessing nodes according to their structural order (by using the 'firstChild' and 'lastChild' properties, for example) an inefficient and potentially unreliable approach? What alternatives are available? We have been accessing nodes by going through a series of firstChild and lastChild properties. This can work, but it is verbose and easy to break ― if we add another node at the start of our document, document.body.firstChild no longer refers to the h1 element, and code which assumes it does will go wrong. On top of that, some browsers will add text-nodes for things like spaces and newlines between tags, while others do not, so that the exact layout of the DOM tree can vary. An alternative to this is to give elements that you need to have access to an id attribute. We can get the element by calling getElementById function.
  2. How does CSS play a role in JavaScript's interactive possibilities with the DOM? What are a few of the techniques related to this? Closely tied to HTML and the document-object model is the topic of style-sheets. It is a big topic, and I will not discuss it entirely, but some understanding of style-sheets is necessary for a lot of interesting JavaScript techniques, so we will go over the basics. In old-fashioned HTML, the only way to change the appearance of elements in a document was to give them extra attributes or to wrap them in extra tags, such as center to center them horizontally, or font to change the font style or colour. Most of the time, this meant that if you wanted the paragraphs or the tables in your document to look a certain way, you had to add a bunch of attributes and tags to every single one of them. This quickly adds a lot of noise to such documents, and makes them very painful to write or change by hand. Style-sheets are a way to make statements like 'in this document, all paragraphs use the Comic Sans font, and are purple, and all tables have a thick green border'. You specify them once, at the top of the document or in a separate file, and they affect the whole document. Classes are a concept related to styles. If you have different kinds of paragraphs, ugly ones and nice ones for example, setting the style for all p elements is not what you want, so classes can be used to distinguish between them. And this is also the meaning of the className property which was briefly mentioned for the setNodeAttribute function. The style attribute can be used to add a piece of style directly to an element. There is much more to styles: Some styles are inherited by child nodes from parent nodes, and interfere with each other in complex and interesting ways, but for the purpose of DOM programming, the most important thing to know is that each DOM node has a style property, which can be used to manipulate the style of that node, and that there are a few kinds of styles that can be used to make nodes do extraordinary things.
  3. Identify some of the browser events JavaScript is capable of interpreting. What might the practical applications be? There are many browser events that JavaScript is capable of interpreting. First one that we can think of straight away is button click. This does in fact work across browsers, but it has an important drawback ― you can only attach one handler to an element. Most of the time, one is enough, but there are cases, especially when a program has to be able to work together with other programs (which might also be adding handlers), that this is annoying.

Homework

  • Write a function asHTML which, when given a DOM node, produces a string representing the HTML text for that node and its children. You may ignore attributes, just show nodes as <nodename>. The escapeHTML function from chapter 10 is available to properly escape the content of text nodes. Hint: Recursion!

    174-homework1.html (Source)

    <!DOCTYPE HTML>
    <html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
        <title>JavaScript 101</title>
        <script type="text/javascript">
            function load()
            {
    
                function forEach(array, action) {
                    var i;
                    for (i = 0; i < array.length; i++) {
                        action(array[i]);
                    }
                }
    
                function escapeHTML(text) {
                    var replacements = [["&", "&amp;"], ["\"", "&quot;"],
                                       ["<", "&lt;"], [">", "&gt;"]];
                    forEach(replacements, function(replace) {
                        while (text.indexOf(replace[0]) != -1) {
                            text = text.replace(replace[0], replace[1]);
                        }
                    });
                    return text;
                }
    
                function isTextNode(node) {
                    return node.nodeType == 3;
                }
    
                function map(func, array) {
                    var result = [];
                    forEach(array, function (element) {
                        result.push(func(element));
                    });
                    return result;
                }
                var first = true;
                function asHTML(node) {
                    if (first) {
                        node.innerHTML = node.innerHTML.replace(
                          /\B\s\B|[\n\r\t]/g,'');
                        first = false;
                    }
    
                    if (isTextNode(node))
                        return escapeHTML(node.nodeValue);
                    else if (node.childNodes.length == 0)
                        return "<" + node.nodeName + "/>";
                    else
                        return "<" + node.nodeName + ">" +
                            map(asHTML, node.childNodes).join("") +
                            "</" + node.nodeName + ">";
                }
    
                console.log(asHTML(document.body));
    
            }
    
        </script>
    </head>
    <body onload="load()">
        <h1>This is a header!</h1>
        <p id="excitingText">
            This is a paragraph! <em>Excitement</em>!
        </p>
        <p>
            This is also a paragraph, but it's not nearly as exciting as the
            last one.
        </p>
    </body>
    </html>
    
  • Write the convenient function removeElement which removes the DOM node it is given as an argument from its parent node.

    174-homework2.html (Source)

    <!DOCTYPE HTML>
    <html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
        <title>JavaScript 101</title>
        <script type="text/javascript">
            function load()
            {
    
                function removeElement(node) {
                    parent = node.parentNode;
                    if (parent) {
                        parent.removeChild(node);
                    }
                }
                console.log(removeElement(document.body.childNodes[1]));
    
            }
        </script>
    </head>
    <body onload="load()">
        <h1>This is a header!</h1>
        <p id="excitingText">
            This is a paragraph! <em>Excitement</em>!
        </p>
        <p>
            This is also a paragraph, but it's not nearly as exciting as the
            last one.
        </p>
    </body>
    </html>
    
  • Write a function called registerEventHandler to wrap the incompatibilities of these two models. It takes three arguments: first a DOM node that the handler should be attached to, then the name of the event type, such as "click" or "keypress", and finally the handler function. To determine which method should be called, look for the methods themselves ― if the DOM node has a method called attachEvent, you may assume that this is the correct method. Note that this is much preferable to directly checking whether the browser is Internet Explorer. If a new browser arrives which uses Internet Explorer's model, or Internet Explorer suddenly switches to the standard model, the code will still work. Both are rather unlikely, of course, but doing something in a smart way never hurts.

    174-homework3.js (Source)

    function registerEventHandler(node, eventType, handler) {
        if (typeof node.attachEvent === 'function') {
            node.attachEvent("on" + eventType, handler);
        } else {
            node.addEventListener(eventType, handler, false);
        }
    }
    
  • Create an HTML page and some Javascript to allow a user to add n numbers. First display a simple form with the question "How many numbers do you want to add (max is 10)". The user should enter a number between 2 to 10 and click on a button in the form. You have to validate the answer. If the user has entered a correct value (between 2 and 10), then dynamically create a form with n text input fields and an "Add" button. Once the form is displayed the user will enter n numbers in the n input fields and when they click on the "Add" button, dynamically create a span element with the result. You will have to perform validation on the values entered in the input fields to make sure that they are numbers. If they are not numbers, display an alert dialogue with an error message.

    174-homework4.html (Source)

    <!DOCTYPE HTML>
    <html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
        <title>JavaScript 101</title>
        <script type="text/javascript">
    
        function createFieldset(id, parent){
            var element = document.createElement('fieldset');
            element.setAttribute('id', id);
            parent.appendChild(element);
            return element;
        }
    
        function createInput(id, parent){
            var element = document.createElement('input');
            element.setAttribute('id', id);
            element.setAttribute('type', 'text');
            parent.appendChild(element);
            return element;
        }
    
        function createButton(id, parent, name, funcName) {
            var element = document.createElement('input');
            element.setAttribute('id', id);
            element.setAttribute('type', 'button');
            element.setAttribute('value', name);
            element.setAttribute('onclick', funcName);
            parent.appendChild(element);
            return element;
        }
    
        function createSpan(id, parent, text){
            var element = document.createElement('span');
            element.setAttribute('id', id);
            var child = document.createTextNode(text);
            element.appendChild(child);
            parent.appendChild(element);
            return element;
        }
    
        function adding(){
            var total = parseInt(document.getElementById('total').value);
            if (total && total < 11 && total > 1) {
                var grandTotal = 0;
                for (var i = 0; i < total; i++) {
                        var number = document.getElementById('input' + i);
                        if (!number) {
                            continue;
                        }
                        var numberValue = parseInt(number.value);
                        if (numberValue) {
                            grandTotal += numberValue;
                        } else {
                            alert('"' + number.value + '" is not an integer');
                        }
                }
                var result = createFieldset('result', document.body);
                createSpan('span', result, grandTotal);
            } else {
                alert('Have you changed the total?');
            }
        }
    
        function submit(){
            var total = parseInt(document.getElementById('total').value);
            if (total && total < 11 && total > 1) {
                var fieldset = createFieldset('fieldsetlists', document.body);
                for (var i = 0; i < total; i++) {
                    createInput('input' + i, fieldset);
                }
                createButton('addButton', fieldset, 'add', 'adding();');
            } else {
                alert('Please enter a number between 2 to 10!');
            }
        }
        </script>
    </head>
    <body>
    <fieldset>
        <p>How many numbers do you want to add (max is 10)</p>
        <input type='text' id='total' />
        <input type='button' value='submit' onclick='submit();'/>
    </fieldset>
    </body>
    </html>
    

On this week, we continue watching 'An Incovenient API - The Theory of the DOM' part 2 as below by Douglas Crockford

Reflection

  • Why is it better to use either trickling or bubbling of events? Why not just give the event to the node on which it was invoked? Trickling is an event capturing pattern which provides compatibility with the Netscape 4 model. Avoid it. On the other hand, bubbling means that the event is given to the target, and then its parent, and then its parent, and so on until the event is cancelled. Bubble is very useful specially we have a very large set of objects. Supposedly we have 100 draggable objects. We could attach 100 sets of event handlers to those objects. Or we could attach one set of event handlers to the container of the 100 objects.

  • Can you think of one situation where you would want to prevent the browser from submitting a form after a user has clicked on the 'submit' button? How would you achieve this? Cancel bubbling is to keep the parent nodes from seeing the event.

    173-reflection1.js (Source)

    e.cancelBubble = true;
    if (e.stopPropagation) {
        e.stopPropagation();
    }
    

    Cancel bubbling is not enough. After all the bubbling is finished, the browser will then do what it's normally does. An event handler as below can prevent a browser action associated with the event (such as submitting a form).

    173-reflection2.js (Source)

    e.returnValue = false; // from Netscape
    if (e.preventDefault) { // from w3c
        e.preventDefault();
    }
    return false; // event handler return false
    

Homework

Since track 1 is the same as track 2 in week 5, the answer for the homework will be in track 2 post.

Since track 2 is the subset for track 1 in week 4, so we combine them both to this post. On this week, beside watching 'An Incovenient API - The Theory of the DOM' as below by Douglas Crockford, we also need to reading these articles below on understanding on DOM.

Reflection

  1. There were two key innovations to the original (fetch-parse-flow-paint) linear workflow that the Mosaic browser used to render web pages. One allowed for a perception of faster rendering, and the other allowed for us to use AJAX. Explain both? This article, The Inconvenient Truth on website performance, do explain clearly.
  2. What are the roles of 'name' and 'id' attributes in HTML tags? What is an appropriate use of both? From bytes's forum, Douglas Crockford said "name is used to annotate POST data in forms. id is used to identify elements for scripting and styling. Some browsers used them interchangeably, which is confusing."
  3. Which pointers does each node in the DOM tree typically have? From Aticle: Traversing the DOM, each node in the DOM tree typically point to 'parent', 'child' and 'sibling'.
  4. Given a node object from a DOM tree, how do we determine if it is a text node or a regular node? From Aticle: Traversing the DOM, a text node’s nodeName property is "#text".

Homework

  • Download the source for the web page 'http://www.useit.com/about/nographics.html'. In the source page itself, write a Javascript function which counts the number of text nodes in the document and shows the count in an alert dialogue. You can choose how you want to trigger the function (through a button click, link click, or any other event).

    172-homework1.js (Source)

    // from Douglas Crockford's video 'An Incovenient API - The Theory of the DOM'
    // http://video.yahoo.com/watch/111582/992708
    function walkTheDOM(node, func) {
        func(node);
        node = node.firstChild;
        while (node) {
            walkTheDOM(node, func);
            node = node.nextSibling;
        }
    }
    
    function getTextNode() {
        var result = [];
        // http://forums.htmlhelp.com/index.php?showtopic=5173
        var someElementRef = document.getElementsByTagName('body')[0];
        // remove all the spaces and new lines
        someElementRef.innerHTML = someElementRef.innerHTML.replace(
          /\B\s\B|[\n\r\t]/g, '');
        walkTheDOM(someElementRef, function(node) {
            var nodeName = node.nodeName;
            if (nodeName === '#text') {
                result.push(node);
            }
        });
        return result;
    }
    
    alert(getTextNode().length);
    
  • Change the example above so that instead of displaying the count in an alert dialogue, it is displayed in a span tag in the HTML page itself.

    172-homework2.js (Source)

    // from Douglas Crockford's video 'An Incovenient API - The Theory of the DOM'
    // http://video.yahoo.com/watch/111582/992708
    function walkTheDOM(node, func) {
        func(node);
        node = node.firstChild;
        while (node) {
            walkTheDOM(node, func);
            node = node.nextSibling;
        }
    }
    
    function getTextNode() {
        var result = [];
        // http://forums.htmlhelp.com/index.php?showtopic=5173
        var someElementRef = document.getElementsByTagName('body')[0];
        // remove all the spaces and new lines
        someElementRef.innerHTML = someElementRef.innerHTML.replace(
          /\B\s\B|[\n\r\t]/g, '');
        walkTheDOM(someElementRef, function(node) {
            var nodeName = node.nodeName;
            if (nodeName === '#text') {
                result.push(node);
            }
        });
        return result;
    }
    
    var total = getTextNode().length;
    var child = document.createTextNode(total);
    var parent = document.createElement('span');
    parent.appendChild(child);
    document.getElementsByTagName('body')[0].lastChild.appendChild(parent);
    
  • Add a link besides the button, such that when the link is click, it changes the style on the span tag to make it's contents bold.

    172-homework3.js (Source)

    // from Douglas Crockford's video 'An Incovenient API - The Theory of the DOM'
    // http://video.yahoo.com/watch/111582/992708
    function walkTheDOM(node, func) {
        func(node);
        node = node.firstChild;
        while (node) {
            walkTheDOM(node, func);
            node = node.nextSibling;
        }
    }
    
    function getTextNode() {
        var result = [];
        // http://forums.htmlhelp.com/index.php?showtopic=5173
        var someElementRef = document.getElementsByTagName('body')[0];
        // remove all the spaces and new lines
        someElementRef.innerHTML = someElementRef.innerHTML.replace(
          /\B\s\B|[\n\r\t]/g, '');
        walkTheDOM(someElementRef, function(node) {
            var nodeName = node.nodeName;
            if (nodeName === '#text') {
                result.push(node);
            }
        });
        return result;
    }
    
    // total is not include the newly elements
    var total = getTextNode().length;
    var child = document.createTextNode(total);
    var parent = document.createElement('span');
    parent.setAttribute('id','special_span');
    parent.appendChild(child);
    document.getElementsByTagName('body')[0].lastChild.appendChild(parent);
    
    var bold = document.createTextNode('bold');
    var link = document.createElement('a');
    link.setAttribute('href','#');
    link.setAttribute('onclick',
    'document.getElementById("special_span").innerHTML="<strong>"' +
    '+document.getElementById("special_span").innerHTML+"</strong>"');
    link.appendChild(bold);
    document.getElementsByTagName('body')[0].appendChild(link);
    

On track 2 week 3, we are continuing reading Eloquent Javascript ebook on chapter 6: Functional Programming and JavaScript code style.

Reflection

  1. Why is it helpful to break a programs logic into functions? As programs get bigger, it helps us easy to understand the program logic.
  2. In JavaScript, functions are first class objects. What does it mean to be a first class object? From Wikipedia - First-class object, first class object is an entity that can be passed as a parameter, returned from a subroutine, or assigned into a variable.
  3. What are anonymous functions, and where would you use them? In computing, an anonymous functions is a function (or a subroutine) defined, and possibly called, without being bound to an identifier. They are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions.
  4. Why is it important to follow good code style in your code? From this article, good code style can help in reducing the brittleness of programs.

Homework

Week 3 homework for track 2 are the same as track 1. Here will be the answers that is recommended by JSLint for exercises 6.1 to 6.5. Track 1 will be showing the original answer for exercises 6.1 to 6.5.

  • Ex. 6.1: Write a function countZeroes, which takes an array of numbers as its argument and returns the amount of zeroes that occur in it. Use reduce. Then, write the higher-order function count, which takes an array and a test function as arguments, and returns the amount of elements in the array for which the test function returned true. Re-implement countZeroes using this function.

    171-exercise61a.js (Source)

    function forEach(array, action) {
        var i;
        for (i = 0; i < array.length; i++) {
            action(array[i]);
        }
    }
    
    function reduce(combine, base, array) {
      forEach(array, function (element) {
        base = combine(base, element);
      });
      return base;
    }
    
    function zeroes(a, b) {
        if (b) {
            return a;
        }
        return a + 1;
    }
    
    function countZeroes(numbers) {
        return reduce(zeroes, 0, numbers);
    }
    
    //document.write(countZeroes([1, 3, 0, 6, 0, 0, 0])); // 4
    

    Using count.

    171-exercise61b.js (Source)

    function forEach(array, action) {
        var i;
        for (i = 0; i < array.length; i++) {
            action(array[i]);
        }
    }
    
    function count(array, test) {
        var total = 0;
        forEach(array, function (element) {
            if (test(element)) {
                total += 1;
            }
        });
        return total;
    }
    
    function zeroes(a) {
        return !a;
    }
    
    function countZeroes(numbers) {
        return count(numbers, zeroes);
    }
    
    //document.write(countZeroes([1, 3, 0, 6, 0, 0, 8, 2])); // 3
    
  • Ex. 6.2: Write a function processParagraph that, when given a paragraph string as its argument, checks whether this paragraph is a header. If it is, it strips of the '%' characters and counts their number. Then, it returns an object with two properties, content, which contains the text inside the paragraph, and type, which contains the tag that this paragraph must be wrapped in, "p" for regular paragraphs, "h1" for headers with one '%', and "hX" for headers with X '%' characters. Remember that strings have a charAt method that can be used to look at a specific character inside them.

    171-exercise62.js (Source)

    function processParagraph(paragraph) {
        // check whether this paragraph is header
        var typeString = 'p';
        var header = 0;
        var i;
        var content;
        for (i = 0; i < paragraph.length; i++) {
            if (paragraph.charAt(i) === '%') {
                header += 1;
            } else {
                break;
            }
        }
    
        if (header) {
            typeString = 'h' + header;
            content = paragraph.substr(header + 1);
        } else {
            content = paragraph.substr(header);
        }
    
    
    
        return {'content': content, 'type': typeString};
    }
    // {'content': 'Language', 'type': 'h2'}
    //console.log(processParagraph("%% Language"));
    // {'content': 'A hermit spent ten years writing a program.', 'type': 'p'}
    //console.log(processParagraph("A hermit spent ten years writing a program."));
    // {'content': 'The Book of Programming', 'type': 'h1'}
    //console.log(processParagraph("% The Book of Programming"));
    
  • Ex. 6.3: Build a function splitParagraph which, given a paragraph string, returns an array of paragraph fragments. Think of a good way to represent the fragments. The method indexOf, which searches for a character or sub-string in a string and returns its position, or -1 if not found, will probably be useful in some way here. This is a tricky algorithm, and there are many not-quite-correct or way-too-long ways to describe it. If you run into problems, just think about it for a minute. Try to write inner functions that perform the smaller actions that make up the algorithm.

    171-exercise63.js (Source)

    function splitParagraph(paragraph) {
        var paragraphs = [];
        var start, end, content;
    
        function spliting(first, last, typeString) {
            while (true)  {
                start = paragraph.indexOf(first, 0);
                if (start === -1) {
                    break;
                }
                end = paragraph.indexOf(last, start + 1);
                if (end === -1) {
                    break;
                }
                // content does not have "*"
                content = paragraph.slice(start, end + 1).slice(1, -1);
                paragraph = paragraph.slice(0,
                                paragraph.charAt(start) === " "? start - 1 :start)
                                .concat(paragraph.slice(end + 1));
                paragraphs.push({'content': content, 'type': typeString});
            }
        }
    
        // emphasised part
        spliting("*", "*", "emphasised");
    
        // footnote
        spliting("{", "}", "footnote");
    
        // normal text
        paragraphs.push({'content': paragraph, 'type': 'normal'});
        return paragraphs;
    }
    
    // [{'content': 'million', 'type': 'emphasised'},
    //  {'content': 'mine is almost a lines', 'type': 'normal'}]
    //console.log(splitParagraph("mine is almost a *million* lines"));
    // [{'content': 'Type something!', 'type': 'emphasised'},
    //  {'content': "and shouted '' The student", 'type': 'normal'}]
    //console.log(splitParagraph("and shouted '*Type something!*' The student"));
    // [{'content': 'square', 'type': 'emphasised'},
    //  {'content': 'result', 'type': 'emphasised'},
    //  {'content': 'two and then it again, the is already inaccurate!',
    //   'type': 'normal'}]
    //console.log(splitParagraph("two and then *square* it again, the *result* is
    //already inaccurate!"));
    // [{'content': 'million', 'type': 'footnote'},
    //  {'content': 'mine is almost a lines', 'type': 'normal'}]
    //console.log(splitParagraph("mine is almost a {million} lines"));
    // [{'content': 'square', 'type': 'emphasised'},
    //  {'content': 'result', 'type': 'footnote'},
    //  {'content': 'two and then it again, the is already inaccurate!',
    //   'type': 'normal'}]
    //console.log(splitParagraph("two and then *square* it again, the {result} is
    //already inaccurate!"));
    
  • Ex. 6.4: Looking back at the example HTML document if necessary, write an image function which, when given the location of an image file, will create an img HTML element.

    171-exercise64.js (Source)

    function tag(name, content, attributes) {
      return {name: name, attributes: attributes, content: content};
    }
    
    function image(path) {
      return tag("img", [], {src: path});
    }
    
  • Ex. 6.5: Write a function renderFragment, and use that to implement another function renderParagraph, which takes a paragraph object (with the footnotes already filtered out), and produces the correct HTML element (which might be a paragraph or a header, depending on the type property of the paragraph object). This function might come in useful for rendering the footnote references:

    171-exercise65a.js (Source)

    function footnote(number) {
      return tag("sup", [link("#footnote" + number,
                              String(number))]);
    }
    

    A sup tag will show its content as 'superscript', which means it will be smaller and a little higher than other text. The target of the link will be something like "#footnote1". Links that contain a '#' character refer to 'anchors' within a page, and in this case we will use them to make it so that clicking on the footnote link will take the reader to the bottom of the page, where the footnotes live. The tag to render emphasized fragments with is em, and normal text can be rendered without any extra tags.

    171-exercise65b.js (Source)

    function splitParagraph(paragraph) {
        var paragraphs = [];
        var start, end, content;
    
        function spliting(first, last, typeString) {
            while (true)  {
                start = paragraph.indexOf(first, 0);
                if (start === -1) {
                    break;
                }
                end = paragraph.indexOf(last, start + 1);
                if (end === -1) {
                    break;
                }
                // content does not have "*"
                content = paragraph.slice(start, end + 1).slice(1, -1);
                paragraph = paragraph.slice(0,
                                paragraph.charAt(start) === " "? start - 1 :start)
                                .concat(paragraph.slice(end + 1));
                paragraphs.push({'content': content, 'type': typeString});
            }
        }
    
        // emphasised part
        spliting("*", "*", "emphasised");
    
        // footnote
        spliting("{", "}", "footnote");
    
        // normal text
        paragraphs.push({'content': paragraph, 'type': 'normal'});
        return paragraphs;
    }
    
    function forEach(array, action) {
        var i;
        for (i = 0; i < array.length; i++) {
            action(array[i]);
        }
    }
    
    function map(func, array) {
        var result = [];
        forEach(array, function (element) {
            result.push(func(element));
        });
        return result;
    }
    
    function tag(name, content, attributes) {
        return {name: name, attributes: attributes, content: content};
    }
    
    function link(target, text) {
        return tag("a", [text], {href: target});
    }
    
    function footnote(number) {
        return tag("sup", [link("#footnote" + number,
                              String(number))]);
    }
    
    function renderFragment(fragment) {
        var content;
        switch (fragment.type) {
            case "emphasised":
                content = tag("em", [fragment.content]);
                break;
            case "footnote":
                content = footnote(fragment.content);
                break;
            default: // case 'normal'
                content = fragment.content;
                break;
        }
        return content;
    }
    
    // {'content': 'A hermit spent ten years writing a program.', 'type': 'p'}
    // {'content': 'two and then *square* it again, the {result} is already
    // inaccurate!', 'type': 'p'}
    function renderParagraph(paragraph) {
        // [{'content': 'square', 'type': 'emphasised'},
        //  {'content': 'result', 'type': 'footnote'},
        //  {'content': 'two and then it again, the is already inaccurate!',
        //   'type': 'normal'}]
        var fragments = splitParagraph(paragraph.content);
        return tag(paragraph.type, map(renderFragment, fragments));
    }
    
    //console.log(renderParagraph({'content': 'two and then *square* it again, the
    //{result} is already inaccurate!', 'type': 'p'}));