Share Tweet Reccomend

Getting Data From the Wikipedia API Using jQuery

Where would we be without Wikipedia? It’s hard to believe how we survived without this icon of the Internet. A novel idea of being an encyclopedia that anyone can edit, it’s always kinda interesting how you can look up an article about one thing and then end up somewhere completely different as you jump from article to article by clicking through its link-heavy content. But more important than that, Wikipedia is the authoritative mediating source of arbitration in all Internet arguments where the combatants usually don’t have anything other than extremely biased and inflammatory blogs as source material at hand and are too lazy to do their own research using actual respectable academic sources.

I’ve even heard that this spills over into the “real world.” Wikipedia has reported that it sees a huge spike in traffic coming in on mobile devices on Friday and Saturday nights and the underlying cause of this is believed to be attempts to settle disagreements than break out from drunken arguments in bars.

Wikipedia

So, all things considered Wikipedia usually has a good base on information just about any subject under the sun. And it got me thinking that a lot of websites and applications could benefit greatly from having an easy way to pull data from Wikipedia and use it to populate content. Fortunately, Wikipedia is built on some software that does provide an API for doing this. I remember seeing the super-slick Google Chrome experiment 100,000 stars put out by the folks at Google used Wikipedia excerpts as a brief description of each star. So I thought I’d look into the process of pulling data from Wikipedia using JavaScript and write it down because I figure someone else would find it useful at some point. Because other wikis are built upon the same foundation as Wikipedia, itself, this is not limited to getting data from Wikipedia alone. You can query other Wikis as well.

Read More »

Share Tweet Reccomend

JavaScript Templates with Handlebars.js

Templates are a very important part of modern day web applications written in JavaScript. Templating essentially encompasses the visual UI (user interface) components of these applications by rendering different “views” depending on the current state of the application. A “view” can be thought of as a certain type of layout. For example, when you sign in to an application and go to your account settings, you might be looking at a “profile” view. Or, if you were using an e-commerce application and you were browsing the site’s inventory, you might be looking at a “products” view. These views are dynamic in nature because they receive data that gets sent to them and then they render that data out in a manner that is meaningful and useful to the user.

There are many different templating libraries that can be used to render views in a JavaScript web application. No one library is necessarily better than another and it is likely that they all have their various strengths and weaknesses. We have looked at a couple of ways to do templates in Backbone.js applications and we’ll revisit one of the libraries used there: Handlebars.js. Handlebars is one of the templating libraries that I like very much for it’s simplicity and intuitive syntax. The Handlebars.js homepage has some very clear straightforward examples that allow you to jump right in to learning how to use it.

Handlebars template setups will look something like the following…

<!DOCTYPE html>
<html>
<head>
<title>Handlebars</title>
<script src="js/jquery.js" type="text/javascript"></script> 
<script src="js/handlebars.js" type="text/javascript"></script> 
</head>
<body>
  
<div class="content"></div>
 
<script id="artist-list-template" type="text/x-handlebars-template">
 
<h1>{{ title }}</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Hometown</th>
      <th>Favorite Color</th>
    </tr>
  </thead>
  <tbody>
      {{#each artists}}
      <tr>
          <td>{{ name }}</td>
          <td>{{ hometown }}</td>
          <td>{{ favoriteColor }}</td>
      </tr>
      {{/each}}
  </tbody>
</table>
</script>
 
</script>
  
  
<script type="text/javascript">
var data = {
    title: 'Artist Table', 
    artists: [
        { id: 1, name: 'Notorious BIG', birthday: 'May 21, 1972', hometown: 'Brooklyn, NY', favoriteColor: 'green' },
        { id: 2, name: 'Mike Jones', birthday: 'January 6, 1981', hometown: 'Houston, TX', favoriteColor: 'blue' },
        { id: 3, name: 'Taylor Swift', birthday: 'December 13, 1989', hometown: 'Reading, PA', favoriteColor: 'red' }
    ]
}
 
var source = jQuery('#artist-list-template').html();
var template = Handlebars.compile(source);
var html = template(data);
jQuery('.content').html(html);
 
</script>
</body>
</html> 

What we are doing here is passing data (in this case the JSON object in our data into) our artist list template (the one with id: #artist-list-template). Note that with our array or artists inside the {{ #each artists }} block (where we are looping over an array of JSON objects) the context has changed so we can directly refer to the artist name, hometown, and favoriteColor properties in for each item

In this example, we are using a static data object that we have created inline but in a real application it’s likely that you’d be getting that data via AJAX requests to APIs somewhere. But whether you get your data from a server or create it locally, the important part is that data can then be passed into the Handlebars template to be displayed by Handlebars. That is where using a templating engine becomes very efficient and very useful. The view/template does not need to worry about handing anything in the data. All of the code to handle getting data and then searching and sorting through it can be handled elsewhere. All your Handlebars template has to worry about is displaying the “final result” that your code generated elsewhere has produced.

There is also support for doing “multi-level” references of you have a JSON object that is x layers deep, you can refer to the properties inside it by normal dot syntax you might be familiar with.

<div class="entry">
  <h1>{{title}}</h1>
  <h2>By {{author.name}}</h2>

  <div class="body">
    {{body}}
  </div>
</div>

<script type="text/javascript">
var data = {
  title: "A Blog Post!",
  author: {
    id: 42,
    name: "Joe Smith"
  },
  body: "This is the text of the blog post"
};
</script>

And there is even the possibility of doing conditionals via the built-in helper methods. For example, here is an if conditional in a Handlebars template where if a property does not exist or is null in an object that is passed to the view, a different “block” of code will be rendered.

<div class="entry">
  {{#if author}}
    <h1>{{firstName}} {{lastName}}</h1>
  {{else}}
    <h1>Unknown Author</h1>
  {{/if}}
</div>

And this is just scratching the surface. There are many other features and functionality that Handlebars.js provides. So head on over to the Handlebars.js homepage to start taking a look through the examples there to see what can be accomplished.

As we have seen Handlebars.js is very useful for creating a view layer in single-page JavaScript applications. Ember.js applications Handlebars.js by default, but you could certainly integrate Handlebars into applications built with other libraries. One of these examples is discussed here. But it should also be noted that there is also support for using Handlebars to render HTML on the server in a Node.js application before it is sent to the browser. For example, if you were building an Express.js application, you could use the express-handlebars module to handle the view component of your appplication by creating some dynamically generated HTML to server up to the browser. For more info on Node.js see this entry here, and for more info on building Express.js applications on top of Node.js see this entry here.

Hopefully you have found this discussion of Handlebars.js useful and that you consider using it for your templating needs in your next application. Download the files below to play around with this useful library…

Download Files
Share Tweet Reccomend

URL Information in JavaScript

Sometimes it is important to get information about the current URL using JavaScript… whether it be the current location, weather a certain query string parameter exists, or just about anything else. It is often the case that you need to know this information on the client-side in your webpage or application.

You could definitely write a bunch of different functions to handle this, but since getting or setting URL-related stuff in JavaScript shares a common area of functionality, it’s probably better to group them all together. For this it is reccomended that we use something like the JavaScript modules approach discussed here. That way we can group everything together.

So below is a starter module called urlInformation. Everything is namespaced to that variable…

var urlInformation = (function () {

    var urlContains = function (pathArray) {

        for (var i = 0; i < pathArray.length; i++) {
            if (window.location.href.indexOf(pathArray[i]) === -1 && window.location.href.indexOf(pathArray[i].toLowerCase()) === -1) {
                return false;
            }
        }
        // did we reach the end? everything passed
        return true;
    };

    var hasParameter = function (name) {
        
        // Get query string
        fullQString = window.location.search.substring(1);

        paramCount = 0;
        queryStringComplete = "?";

        if (fullQString.length > 0) {
            
            // Split string
            paramArray = fullQString.split("&");

            //Loop through params, check if parameter exists.  
            for (i = 0; i < paramArray.length; i++) {
                currentParameter = paramArray[i].split("=");
                if (currentParameter[0] == name) //Parameter already exists in current url
                {
                    return true;
                }
            }
        }

        return false;

    };

    var getParameter = function (name) {
        var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
    };

    return {
        getParameter: getParameter,
        hasParameter: hasParameter,
        urlContains: urlContains
    };

})();

As we can see here, we have some methods (psuedomethods really) on this mobile that we can call directly anywhere in our code like so…

urlInformation.getParameter('id');

This will return the value of the “id” parameter that is appended to the query string in the URL ?type=something&id=7.

What’s great about this approach is that we can easily add any methods we want, using any variables we want, and as long as we add it to the return object we are in good shape. For example, we could expand our mobile below and add a hash function that gets the current value of the #hash in the URL…

var urlInformation = (function () {

    var urlContains = function (pathArray) {

        for (var i = 0; i < pathArray.length; i++) {
            if (window.location.href.indexOf(pathArray[i]) === -1 && window.location.href.indexOf(pathArray[i].toLowerCase()) === -1) {
                return false;
            }
        }
        // did we reach the end? everything passed
        return true;
    };

    var hasParameter = function (name) {
        
        // Get query string
        fullQString = window.location.search.substring(1);

        paramCount = 0;
        queryStringComplete = "?";

        if (fullQString.length > 0) {
            
            // Split string
            paramArray = fullQString.split("&");

            //Loop through params, check if parameter exists.  
            for (i = 0; i < paramArray.length; i++) {
                currentParameter = paramArray[i].split("=");
                if (currentParameter[0] == name) //Parameter already exists in current url
                {
                    return true;
                }
            }
        }

        return false;

    };

    var getParameter = function (name) {
        var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
    };

    var getHash = function () {
        return window.location.hash;
    };

    return {
        getParameter: getParameter,
        hasParameter: hasParameter,
        urlContains: urlContains,
        getHash: getHash
    };

})();

And then we can call it like so..

urlInformation.getHash();

to get the current hash in the URL.

Share Tweet Reccomend

Crunching Tables, Hidden Data

Should I give up, or should I just keep crunching tables, even if it leads nowhere?

Ah tables… a fascinating piece of Internet history. Originally conceived for the purposes of displaying data, once upon a time, tables, due to their stability, were even the dominant design structure of the Internet. But now with so many other options for both design and displaying data in the HTML DOM, tables are a relic of the past, right?

A lot of times, it seems like this is true. However, there are still situations you run into where you’ll come across tables in legacy systems that still use them as a holdover from past older versions of the product, or even more modern data-display centric systems. One example of this is actually a pretty popular large-scale solution among a diversity of organizations. I won’t name any names, but it rhymes with “Icrosoft Airpoint”

Tables have issues with the fact that the web has been going more mobile since the latter half of the 2000’s and thus, display and viewing areas have been getting smaller. The difficulty with this is that tables are, by their nature, not a particularly fluid data structures. They can be flexible to an extent, but at some point they just decide to say “no más” and they’ll overflow their container content areas… which usually equals some fun side-scrolling.

So here we’ll enter into a discussion of some issues with tables and what can be done to solve them. It seems like the natural approach that a lot of developers will take toward tables to set the width to 100% in the CSS.

table{
width:100%;
}

This is fine up to a certain point as shown in the first example here.

However as the number of columns grow or the data within them start to contain more data that’s not really “breakable” e.g. long words or even hyperlinks eventually tables just overflow their containers as shown in the next example.

Setting width:100%; in your CSS does nothing. Even setting a fixed width such as width:500px; doesn’t do much good either.

What can be done? Well there are a number of solutions perhaps not all of them ideal, but if you’re stuck using tables and you don’t have much choice in turning to something else, what follows can be helpful, at least a little bit.

Solution #1: Crunch it in There
Surprisingly, there is a way to actually ensure that your table does fit the content area. This can be accomplished by setting the table-layout property to “fixed”.

table{
table-layout: fixed;
}

There is a downside to this: all the columns now have the same width. Although this looks okay, it can actually be improved upon a bit further by adding the word-wrap: break-word, property.

table{
table-layout: fixed;
word-wrap: break-word;
}

You could even go a bit further and hide overflowing content in your table header cells and table data cells.

table tr th, table tr td {
overflow:hidden;
}

This, like other solutions with tables does not seem ideal. However, if there is a need to crunch your entire table into a small section, this can be a compromising way to do it.

Solution #2: Side-Scroll
By adding overflow-x: scroll to your container div that your table lives within you can get a little bit of side-scrolling action on.

.container {
overflow-x:scroll
}

Solution #3: Show Less Content
The other option would be to show less content. This can be done by either setting class names on the columns and cells and then hiding the ones you don’t want to show at smaller resolutions (such as those found on mobile devices) by making use of CSS3 media queries.

Solution #4: JavaScript
Another option would be to use a JavaScript/jQuery plugin of some sort to either rearrange your table data or show a limited amount in certain circumstances.

All in all you do have a number of choices you can pick from in dealing with tables, especially when you have to make design decisions pertaining to mobile devices. What the best option is for your particular solution will probably depend on a number of things, but hopefully some of the ones discussed above will give you a good starting point to jump off from.

Share Tweet Reccomend

JavaScript Replacement for Deprecated arguments.callee

As JavaScript continues to evolve, a long time mainstay of JavaScript, arguments.callee, is going by the wayside. Depending on the time you are reading this, it may have already. arguments.callee was/is a way for JavaScript developers to have a function call itself when there might be some cases when the name of the function is not known or it’s an unnamed anonymous function. As is stated in the Mozilla Developer Network article

callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is useful when the name of the function is unknown, such as within a function expression with no name (also called “anonymous functions”).

John Resig, know for his involvement with the jQuery project, used it in earlier versions his discussion/example on a pattern of JavaScript inheritance.

/* Simple JavaScript Inheritance
 * By John Resig https://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
 
  // The base Class implementation (does nothing)
  this.Class = function(){};
 
  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;
   
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
   
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
           
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
           
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;
           
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
   
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
   
    // Populate our constructed prototype object
    Class.prototype = prototype;
   
    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;
 
    // And make this class extendable
    Class.extend = arguments.callee;
   
    return Class;
  };
})();

This pattern of adding an “extend” property to an object, is recognizable in other JavaScript projects such as Backbone.js.

Class.extend = arguments.callee;

With arguments.callee being deprecated, What can we do to replace it? The solution can be found in named function expressions. Without going into too much detail about what they are, in the code above. We can change this part…

Class.extend = function(prop) { 
...
}

to the following…

Class.extend = function extender(prop) { 
...
}

Then instead of using arcuments.callee at the bottom we can use…

Class.extend = extender;

By using a named function expression, we have replaced arguments.callee. In doing this we can modernize our applications and sentimentally waive goodbye to relics of the past.