— Tech+Life+Music

On the topic of making Internet Explorer behave, one of the easiest things you can do to make sure the dreaded Internet Explorer 6 is up to reasonable snuff is to include a single Javascript snippet on your page.

Chrome Frame

The Google Chrome Frame is not new. It’s an IE plugin that acts as an additional rendering engine that delivers more or less the same features, offerings, and HTML5 + CSS3 goodness as the standard Google Chrome. Long story short, it’s a Google Chrome running inside your Internet Explorer. The ultimate problem was that it needed to be installed by a user with administrative rights.

And then the “non-admin” Chrome Frame came around. It’s a Chrome Frame that can be installed by any user on a client computer. Now, there’s virtually no reason anymore not to install it if you’re stuck on a legacy Internet Explorer for some reason.

Getting users to install Chrome Frame

Now, in order to be able to deliver all the cutting-edge HTML 5 rainbow goodness for your clients, you just have to make sure that install the Google Chrome Frame. How to do that?

Just include the following inside your markup, preferably right before the closing tag:

<!--[if lt IE 7 ]>
  <script src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js"></script>
  <script>window.attachEvent("onload",function(){CFInstall.check({mode:"overlay"})})</script>
<![endif]-->

That’s pretty much it. If your webpage is loaded inside an Internet Explorer 6 or lower, a very prominent overlay attempts to convince your user to install Chrome Frame.

Learning from the HTML5 Boilerplate, Part 3

Of course, to make the most use of Chrome Frame, you’ll have to include the appropriate X-UA-Compatible value as detailed in this HTML5 Boilerplate article.

If you want to know more about the Google Chrome Frame, hop on over to the FAQ.

Read More

About SOPA and PIPA, aka Why the Blackout aka On Being Filipino

This blog is written by a Filipino, maintained by a Filipino, and proudly Filipino. Most of the content were typed by my own hand, code crafted by my own mind, and none of it is infringing copyright in whatsoever way (hooray for open source).

So why the blackout? Why the care for stopping SOPA and PIPA?

Read More

The HTML5 Boilerplate is well-known across web programmers as a powerful starting template for (as the project homepage puts it) building fast, robust, future-proof sites. Out of the box, it provides HTML, CSS and Javascript code arranged in such a way to drive as much oomph into your pages as possible. Every nook, cranny, and design decision borrows from widely-accepted standards, and is supported by countless hours of research and testing.

While the HTML5 Boilerplate is awesome as a starting foundation for building awesome sites, it is also packed with code snippets and patterns you should be using for your projects. Just in case you’re not using the HTML5 Boilerplate for some reason.

Read More

The HTML5 Boilerplate is well-known across web programmers as a powerful starting template for (as the project homepage puts it) building fast, robust, future-proof sites. Out of the box, it provides HTML, CSS and Javascript code arranged in such a way to drive as much oomph into your pages as possible. Every nook, cranny, and design decision borrows from widely-accepted standards, and is supported by countless hours of research and testing.

While the HTML5 Boilerplate is awesome as a starting foundation for building awesome sites, it is also packed with code snippets and patterns you should be using for your projects. Just in case you’re not using the HTML5 Boilerplate for some reason.

Read More

The latest version of jQuery (that is, 1.7.1, or 1.7.x) has been around for a good while already, and the new .on() and .off() functions still come to me as the shiniest new toys that came along with it. Not only are they shorter, more intuitive and better at what they do, but they also promote (generally) accepted jQuery good practice that has been around for quite a while.

What am I talking about?

If you’re any jQuery programmer worth your salt, then you know of, at the very least, .bind() and .live() when it comes to DOM event handling. The main difference being that the former is preferred for present elements, and the latter is “mandatory” for future element handling.

One or two rungs up the jQuery programmer ladder, and you’d know of .delegate() as well. If you actually use it with convicted priority over .live(), then you’re golden. An explanation of why would require a good grasp of how jQuery handles events behind the scenes, followed by a primer on why using .live() is bad.

It’s admittedly a pet peeve of mine. And I’d like to think that the reason why .live() persists so sturdily when .delegate() is most clearly a better choice (aside from the fact that the latter was introduced one major version step later in the jQuery lifetime), is that .live() is so much easier to type.

Isn’t it? I mean look at it.

// live
$('a').live('click', do_backflips);
 
// delegate
$(document).delegate('a', 'click', do_backflips);

Sheer convenience.

.on() and .off()

Which is a big reason why I -heart heart heart- the new .on() and .off() functions in jQuery 1.7.x. It streamlines all your event handling into just two functions, whether or not you’re taking into account present or future elements.

If you’re not familiar, the usage for .on() is like this:

// for present elements
$('a').on('click', do_backflips);
 
// for future elements
$('#container').on('click', 'a', do_backflips);

I’d suggest you also take a look at the official documentation for the on and off functions as well. Pretty spiffy.

What’s really nice is that both versions of .on() map to .bind() and .delegate() respectively, which has the added benefit of simplifying the question of what function to use on any given case, and cleaning up syntax. And, hey, it’s also easy and intuitive to use.

Additionally, .live() has also been deprecated as of jQuery 1.7.x. I quote:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

Frankly, one could argue that good practice is being forced down the programmers’ throats. But as it plays on clear improvements on jQuery’s event model, I don’t mind that one bit.

Read More

I’m definitely a sucker for code reuse (as I’d argue all programmers should be).

If you’ve had experience working with setting up WCF services for run-of-the-mill CRUD operations (i.e. adding new entities, getting entities, etc), you know how much of a pain in the behind it is to manually type out code designed to work with a single, specific entity (or aggregate). If you’ve got ten entity types available across your SOA, then you might expect to write at least a service operation tailored for each of them, for each of your CRUD processes.

That’s, in and out of itself, 40 operations that more or less will use the same gist of code.

Reusing CRUD code in WCF services

While your mileage may vary (and in real-life projects, the exact same code across all your operations is significantly unlikely), I’ve had to work with this exact situation a few weeks back (spewing out a Stack Overflow entry in the process) and the eventual solution is spiffy enough not to share.

For a good amount of the time, reusing code just means inheriting a base class, however, in the case of service operations, we can’t tag generic methods / classes (which we really want to use as a base class) as service contracts.

A great workaround, is to utilize three things in writing out your operations: an interface for the contract, a (abstract) base class for the generic methods, and another class to function as the tangible service endpoint.

[ServiceContract]
public interface IPersonServiceContract 
{
    [OperationContract]
    void Add(Person person);
    [OperationContract]
    Person Get(int id);
}
// Entity is our POCO entity base class
public abstract class GenericCrudService<T> where T : Entity
{
    // assuming Entity Framework 4.1 CF
    public void Add(T entity) {
        context.Set<T>().Add(entity);
        context.SaveChanges();
    }
 
    public T Get(int id) {
        return context.Set<T>().Where(x => x.Id == id).FirstOrDefault();
    }
}
// and this will serve as the actual endpoint
public class PersonService : GenericCrudService<Person>, IPersonServiceContract
{
    // no code necessary
}

It’s pretty handy, if you ask me. For all additional endpoints you have to create, all you have to do is write out the service contract via an interface, create the actual endpoint, and have it inherit from the contract and the GenericCrudService using the specific type you need.

Read More

I take my online security very seriously. (You should too.) That means, using HTTPS whenever possible, being wary whenever I’m out on public wifi, and, most importantly, strong passwords on every single site that you identify yourself in; your email most especially.

Unfortunately, one of the very real banes of strong passwords is that they’re generally hard to remember, primarily because they “should” be made up of a cryptic array of characters that seem to follow a rationale that the harder it is for me to recall, the harder it is to crack. I’m guilty of this myself, and I find comfort in having my passwords mimic y@k3n0Ga4Ar@!ad1234 in every single password opportunity I come across.

To remedy this, an XKCD comic from last week suggests doing something completely different from what we’ve grown accustomed of doing in order to create strong passwords that are easy to remember: pick four random words and slap them together.

A compelling idea for creating strong passwords that are easy to remember

The idea has been astute enough that developer Jeff Preshing actually took it upon himself to create an online tool that generates passwords for you, according to the XKCD strip’s specs. (Of course, it’s easy enough to get four random words without an app, but the comments on this article of Preshing’s make for good technical discussions on cryptography, information security and combinatorics.)

Why does this work? Thomas Baekdal‘s article on The Usability of Passwords provides a very thorough discussion on the topic, and I highly recommend reading that for a complete and more accurate explanation. It does a great job of detailing the topic without getting highly technical.

If you’re still not convinced (and wish to stick to complex passwords), then I suggest using something like KeePass or LastPass to help consolidate and remember your passwords in an effectively secure manner.

Read More

One of the ways you can keep readers engaged to your website content is to make sure that links to external sites open to new tabs (or windows). This way, the material they’re engaged in on your site is not erased, they can switch to the newly opened content, and eventually go back to your content (and hopefully continue what they were doing).

However, as websites grow and scale, it can get a little cumbersome to keep track of all the links and manually mark each of them whether or not they open in a new tab. As a case in point, in WordPress (where it’s supposedly pretty easy to do this already), whenever you add a new hyperlink while writing a new article, you have to tick a checkbox to make it open a new tab.

Wouldn’t it be nice to automatically have links open in a new tab (or don’t)? With a bit of jQuery code, we can.

The Code

If you’re itching to jump straight to the code, then here it is, in all it’s -um- glory. Just copy and paste this into your jQuery-enabled page anywhere in between script tags.

jQuery(function($){
    $('a[href^="http://"]')
        .not('[href*="richardneililagan.com"]')
        .attr('target','_blank');
});

Make sure you substitute your own domain name for the richardneililagan.com in there, and you’re all good to go.

If you want to know how that works, read on.

jQuery Magic

What we want to achieve is that when a link pointing outside of our domain is clicked, the linked content is loaded in a new tab. So it’s pretty clear that we want to filter all the links in our site for all those that point outside our domain.

We can do that using simple jQuery selectors:

    // assuming that our domain is RICHARDNEILILAGAN.COM
    var external_links = 
        $('a[href^="http://"]').not('[href*="richardneililagan.com"]');

The first selector (a[href^="http://"]) simply filters for all the links in our page with href values (the URL it links to) that start with http://. External links, unlike internal ones, require http:// for them to properly work, so it’s a good filter for our purposes.

The second filter .not('[href*="richardneililagan.com]') further filters our links by removing those links that have richardneililagan.com (our domain) in them. We’re assuming here that when a link points to something with richardneililagan.com in it, then its internal.

Now, we actually move to making these links open in new tabs. In semantic HTML, to make a link open in a new window/tab, you just have to give it the target = '_blank' attribute pair. So we’re going to do just that, but by using jQuery to do it for us.

    external_links.attr('target','_blank');

With that, all our external links should have been updated target attributes so that they open in new tabs.

Read More

One of the questions I normally get from jQuery learners (aside from why the hell .bind() doesn’t work on dynamically-added HTML elements) is how to write a jQuery plugin. So for this article, I thought I’d introduce a fairly simple step-by-step walkthrough of creating a jQuery plugin that allows us to make something like this really quickly:

Doing this using vanilla jQuery

Of course, you can pretty much do this just by using plain jQuery, just as you would do with most other jQuery functionality. Something like the following would suffice:

// yeap, I know that this code can be optimized a big deal.
jQuery(function($){
 
    // we create two DIVs which form the two parts of our message box
    var $header = $('<div/>').addClass('header').text('Some header'),
        $message = $('<div/>').addClass('message').text('Some message');
 
    // we add the click handler that makes the message slide up and down
    $header.click(function() { $message.slideToggle('fast'); });
 
    // finally, we stick those two DIVs inside some other element
    $('#foo').append($header).append($message);
 
});

With something like that, you’ve pretty much managed to accomplish the same thing.

However, if we want to be able to reuse that piece of code on several other elements, it’d be a better idea to write out that whole jQuery logic into a plugin, so we can just call on it whenever we want.

The basics of extending jQuery

jQuery exposes two kinds of ways to extend it: one using the $ namespace, and the other using $.fn.

Extending the plain $ object allows you to define new utility functions. Adding a new utility function is as easy as just naming a new property:

// creating the "say" utility function
$.say = function (message) {
    alert (message);
};

We can then use that much like any other function by calling $.say('Bros before hoes.');, and it’ll behave as you’d expect it to.

An arguably more powerful way of extending jQuery is extending $.fn, which allows you to create new functions that act on wrapped objects (like, for example, .addClass()). You create new wrapper methods in much the same way you create utility functions:

$.fn.foobar = function () {
    this.text('foobar');
    return this;
}

Inside a new wrapper function, the this object is set to the jQuery wrapped set that the method was called on. So if $('#foo').foobar(); is called, then this inside foobar() is set to $('#foo'). This way, you can manipulate the elements as you see fit.

One of the things you should make a mental note of is to return the this context after the function resolves, so that your new wrapper method is compatible with jQuery chaining. (That is, you can do something like $('#foo').foobar().addClass('bar');.)

Changing our original jQuery code into a plugin

Now that we’ve got the basics out of the way, it should be fairly straightforward to rewrite our code above into a bit of jQuery plugin functionality. Calling our new method slidingBox() and applying the necessary changes in code, we get something like:

(function($){
 
    $.fn.slidingBox = function (header,message) {
 
        var $header = $('<div/>').addClass('header').text(header),
            $message = $('<div/>').addClass('message').text(message);
 
        $header.click(function() { $message.slideToggle('fast'); });
 
        return this.append($header).append($message);
    };
 
})(jQuery);

With that out of the way, we can then use that just by calling something like $('#foo').slidingBox('This is my header.','This is my message.');. With a bit of CSS styling, you’re more or less ready to go!

If you want a more interactive way of demo-ing the code discussed in this article, or if you want to tinker around with ready-made code a bit, then feel free to wreak havoc on a jsFiddle I prepared especially for this article. It’s got ready jQuery code, and some CSS to boot.

Read More

It’s not unusual to cache reusable components in your pages onto variables so that you don’t have to reselect / reevaluate them every single time you have to do something with them.

Let’s say I had a DIV element that I can append paragraphs onto. (Every) Javascript developer worth his/her salt performs some bit of namespacing to the effect of:

<div id="foo"><!-- BLAH --></div>
var app = {
    foo : $('#foo')
};

This way, whenever I’d want to reference that DIV again, I’ll just have to call it via app.foo. I’m actively refraining from polluting the global namespace with a slew of variables for all the elements I want cached, and I have a ready jQuery element that doesn’t need re-selection every time I want to use it.

Adding in functionality

Now, say that I want to add in the functionality to actually add in the paragraphs into my DIV. I can achieve that by doing something like:

var addParagraph = function (text) {
    var myParagraph = $('<p></p>').text(text);
    app.foo.append(myParagraph);
};

… which is perfectly valid since app.foo is, in itself, a valid jQuery object. Improving on that a bit, I’d personally stick that function into the namespace I created prior, so that I don’t add unnecessary global objects.

var app = {
    foo : $('#foo'),
    addParagraph : function (text) {
        var myParagraph = $('<p></p>').text(text);
        app.foo.append(myParagraph);
    } 
};

Making it even better

That’s good. But if you’re a stickler for code (as I am), you’ll probably be itching to structure the code so that app.foo owns the addParagraph function. It makes better sense to have a function that acts on an object alone to be within scope of said object. I’ve got you.

One way to go about it is something like :

app.foo.addParagraph = function (text) {
    var myParagraph = $('<p></p>').text(text);
    this.append(myParagraph);
};

… and that on its own isn’t exactly bad, as you’re getting exactly what you want done. However, the way I’d recommend it most of the time is by using jQuery’s $.extend() function.

$.extend(app.foo, {
    addParagraph : function (text) {
        var myParagraph = $('<p></p>').text(text);
        this.append(myParagraph);
    }
});

$.extend() isn’t something that a lot of jQuery programmers bother with (at least, I think so), but it accomplishes more or less exactly the same thing. So why, then, should I use the $.extend()?

  1. It’s cleaner and easier to add in multiple functionalities at once.

    If I wanted to add in more stuff, like add, edit and remove paragraph functionalities into my object, my code would most probably end up a mess. Not that it’s not possible, but it’s a bit of a maintainance nightmare to have to code something like

    app.foo.add = function () {};
    app.foo.edit = function () {};
    app.foo.remove = function () {};
    // ... some more functions

    I’d rather see something like

    $.extend(app.foo, {
        add : function () {},
        edit : function () {},
        remove : function () {}
    });

    … and since we’re technically working with a plain JSON object as $.extend()‘s second parameter, it’s perfectly valid to go this path :

    var paragraphFunctions = {
        add : function () {},
        edit : function () {},
        remove : function () {}
    };
     
    $.extend(app.foo, paragraphFunctions);

    Wouldn’t you agree that that’s much easier to look at and take care of?

  2. It’s easier to work with multiple components that share the same functionality.

    Not only is it easier to slap on multiple functionalities on one object, but it’s also easier to slap on the same functionalities onto multiple objects.

    If I had two of those DIVs, then traditionally I’d have to do something like this:

    var app = {
        foo : $('#foo'),
        bar : $('#bar')
    };
     
    app.foo.add = function () {};
    app.foo.edit = function () {};
    app.foo.remove = function () {};
     
    app.bar.add = function () {};
    app.bar.edit = function () {};
    app.bar.remove = function () {};
     
    // yeap, I know that that's kind of a stretch

    A more convenient method would be to cache a JSON object with the common functionalities, and use $.extend to slap those onto the relevant components.

    var paragraphFunctions = {
        add : function () {},
        edit : function () {},
        remove : function () {}
    };
     
    $.extend(app.foo, paragraphFunctions);
    $.extend(app.bar, paragraphFunctions);

    Of course, you could also utilize Javascript prototyping at a lower level to achieve the same thing, but this is a somewhat quicker (and less complex) way of doing that.

You can check out a very rudimentary example of making it all work over on jsFiddle.

Read More