Home > Monthly Archives: December 2011
Page 1

Switch on With jQuery’s New Event Methods

The latest version of jQuery, version 1.7.1 at the time of writing, has completely overhauled its event system, giving us just two new methods to replace all existing event methods such as bind(), live() or delegate().

Event handling has been a core part of jQuery for a long time, but over the years the jQuery event landscape has flourished and grown, with successive releases increasing the number of methods for handling events.

The new event methods on() and off() condense these different methods down into a single unified API. Instead of having different methods to handle different behaviours, the new methods simply behave differently depending on how they are called.

Attaching events like bind()

Attaching an event using the on() method in the same way as if we had used the bind() method can be done like this:

$("#button1").on("click", function () { //do stuff });

When just two arguments are passed to the on() method the event handler is attached directly to the selected element. In this example the button with an id of button1 will have a click-handler attached to it, which will execution the function passed as the second argument whenever the event is detected. This is equivalent to the now deprecated bind() method. Alternatively, we can attach multiple events by supplying a single argument to on():

$("#button1").on({ click: function () { //do stuff }, focus: function () { //do stuff } });

The argument we pass to the method accepts an object where the keys are event names, and the values are anonymous functions that are executed when the events are detected. Again, this is exactly how we could have previously used bind().

Attaching events like delegate()

In its other form, the on() method accepts three arguments:

$("#delegateContainer").on("click", "button", function () { //do stuff });

In this form the on() method accepts an extra argument. The first argument is still the name of an event (or a space-separated list of events) to listen for, but the second argument is now a selector to filter by. The third argument is the function to execute when the event (or events) is detected.

What happens is; the container element that is initially selected (“delegateContainer” in the above example) has the event handler attached to it. When the named event is detected jQuery checks to see whether it originated from the element matching the selector passed as the second argument. If it does, the function is executed.

Just like with the delegate() method, we can use any CSS selector, DOM node or jQuery object as the second argument. This is a major step up from the live() method, which was restricted to just CSS selectors. However, the value of $(this) within the event handler changes depending on what you pass as the second argument; if you pass a CSS selector, the $(this) object points to the innermost element that triggered the event (in this example, the button that was clicked). However, if you pass a DOM node or jQuery object, $(this) will point to the container that the event was delegated to. Watch out for this when coding.

Event delegation in this way brings several benefits; firstly, it can allow us to vastly reduce the number of event handlers that are attached to elements – we could have hundreds of buttons within our delegateContainer, but we would still only need to attach a single handler to the container, and any button would trigger it when clicked. Secondly, if we attached new buttons at some point in the future, after we had attached the handler, the new buttons would still trigger the event handler without us having to rebind it.

As well as the arguments we’ve looked at, the on() method can also accept a data object, which will available within the callback function as event.data. This argument should be passed to the method as either the second or third argument depending on whether a CSS selector is also provided, for example either:

$("#button1").on("click", { someKey: "someValue" }, function (e) { //someValue available via e.data.someKey });

Or:

$("#button1").on({ click: function (e) { //someValue available via e.data.someKey } }, { someKey: "someValue" });

Or, with event delegation:

$("#delegateContainer").on("click", "button", { someKey: "someValue" }, function (e) { //someValue available via e.data.someKey });

Removing events

To remove a bound event handler, we can use the off() method, which is the new replacement for the unbind(), die() and undelegate(). The off() method also takes a varying number of arguments; if a CSS selector was passed to the on() method, the same selector should be passed to off(). To remove the delegated event handler, we could use the following code:

$("#button3").on("click", function () { $("#delegateContainer").off("click", "button"); });

The off() method is almost identical to the code we used with the on() method from the last example, except that we don’t provide a callback function. If we don’t supply a CSS selector to the on() method, the off() method can be even simpler, with just the name of the event to remove the handler from.

Summary

The old event-handling methods live(), bind() and delegate(), and their opposite unbinding methods, are all now deprecated; they’re still available to use through the core jQuery API of course and will remain there for some time yet, but their use is advised against now that we have on() and off() to take care of all our event handling needs.

...
more →
Greg says: I've noticed that a tonne of people still want to use .live() even though it's a performance nightmare. Although I always advise...

Common C# Build-Time Errors: Part I

Here’s the situation:

You’ve written a program in C#. You’ve checked the flowcharts, examined your coding and developed your user interface.

You’re anticipating that everything will flow as smooth as silk. You’re ready to create a build of the program and, instead of seeing a beautiful, efficient result, you get several (often incomprehensible) error message. How did this happen?

Here are SOME ways that these errors occur:

#1 Undeclared Variables

C# throws an error message on undeclared variables. This most frequently happens in one of three ways:

1) The variable is not assigned a type. The code in a “for-next loop” that reads like this:

for (nextStep = 0; nextStep < 20; nextStep++) { // loop process }

should read like this:

for (int nextStep = 0; nextStep < 20; nextStep++) { // loop process }

2) The variable name is spelled differently. Variables are case sensitive in C#, which can lead to some careless errors:

for (int nextStep = 0; nextStep < 20; nextStep++) { int workerID = nextStep; Console.WriteLine("Worker ID #:" + WorkerId); }

The compiler will view “workerID” and “WorkerId” as two different variables and view “WorkerId” as undeclared.

3) The variable is declared in a different scope. In order to use variables both inside and outside a routine (such as a “for” loop or a “while “ loop), the variable must be declared outside the routine.

for (int nextStep = 0; nextStep < 20; nextStep++) { int workerID = nextStep; } Console.WriteLine("Worker ID #:" + workerID);

This code will not display the final number in the sequence, but will throw an error due to the workerID variable’s declaration sitting inside the for loop.

#2 Variable Conversion Errors

For developers new to C#, especially those coming from more intuitive platforms such as VB.Net or ASP.Net, the lack of flexibility with variable types can be a hurdle.

Here’s an example of a variable conversion that throws a build-time error:

class MyClass { static public float TripleFloat(float t) { float fResult = 3.0 * t; return fResult; } }

Since 3.0 is a “double”-type variable, the operation will return a “double”, not a “float”, and create a build-time error. The operation needs to recast the result as a “float” to avoid the conflict:

class MyClass { static public float TripleFloat(float t) { float fResult = (float)(3.0 * t); return fResult; } }

#3 Protection Level Conflicts

Some programmers may forget that the default protection level for a class is “internal” and the default level for any member in that class is “private”.

class MyFirstClass //default protection = internal { public void NameFunction(){ MySecondClass sc = new MySecondClass(); sc.strFirstName = "Harry"; sc.strLastName = "Potter"; Console.WriteLine("Name: " + sc.strFirstName...
more →
Benjamin Paul says: Surely the Visual Studio IDE should minimise the risk of most of these? These should be clearly obvious to the developer while...

A Look at Responsive Web Design

Responsive web design is widely thought of as a design trend, but it’s much more than that.

It is an approach to web development that allows a website to break itself down smoothly across multiple monitor sizes, screen resolutions, and platforms, be it a computer, tablet or mobile device.  It allows the developer to create a site that is optimized for each platform, both in navigation, readability and load time.

In this tutorial, we take a look at what responsive web design entails for the developer.

Using Multiple Image Sizes

There’s no need for a mobile device to be loading an image that is 1920 px wide by 1200 px tall and a quarter mb.  That will only slow down the time it takes for a viewer to load the site on their mobile device and eat through their monthly data quota.  A great example of a site that keeps their main image but resizes it based off the screen resolution of the viewer is Sony.  You’ll notice, amongst other changes, how the main image has changed in size between the larger version and the mobile version thanks to CSS media queries.

Another approach to quickening load times and determining how things should be displayed on different devices is to completely drop your main image.  That’s exactly what Fork CMS did with their site.  The main image resizes between the widescreen and more traditional square monitor ratio version of the site, but then is completely dropped from the design once you get down to the mobile sized version.  However, I did find it a little interesting that the designers chose to keep the image towards the bottom of the site throughout each version, but drop the main image.  The main image helped establish the site and give it some character, by excluding that main image on the mobile version the site loses a bit of character.

Navigation

Text links are another thing to take in to consideration when developing a responsive website. On a computer text links aren’t a big issue, but once you get to browsing a scaled down version of a site on a mobile phone it can be hard to hit the desired target area of a small text link. Converting a text link to a slightly bigger button, or swapping text for an icon, will make the site more navigable on a touch screen mobile phone.

A good example of a site that’s navigation changes from text links to buttons is the website for the Clean Air Commute Challenge. You’ll see how in the larger, widescreen mode of the site there are four main navigation links across the top of the page. However, once the site is squeezed in to meet the dimensions of a mobile site the text links convert to larger, easier to target, buttons.

To see a good example of a site where the navigation switches from links to icons have a look at the 2011 dConstruct site. Notice how their three main navigation links, Conference, Workshops and Location, change to icons once the site is narrowed to the parameters of a tablet device or mobile phone. This makes it easier for the viewer to navigate the site regardless of what device they’re on. You will also notice with the dConstruct site that the images don’t swap themselves out at certain points, rather they simply grow and shrink on the fly as the page shrinks or grows.

Flexible Dimensions

Optimizing a site to be responsive and change across platforms is easy to do thanks to CSS. With CSS you are able to define the maximum and minimum height and width of elements, allowing them to grow, shrink and adapt to the specific parameters in which the site is being viewed. Setting the width to adapt is also easily achievable by setting your height and width to a percentage.

Working with percentages to size elements of your website can be a little trickier than creating a site where everything has a fixed pixel dimension. However, there is a fairly simple way to determine what the percentage is that you need to define an element of your site. If you are developing a page and want the main content area to be 1,000 px wide at a specific resolution and you want to include a navigation column on the left-hand side that has a width of 200 px, you will have to convert that to a percentage. You can easily convert a fixed pixel size to a percentage by taking the width of the navigation column, dividing it by the full width of the column, then multiplying it by 100. In this instance we would take 200 (the width we want our navigation column), divide it by 1,000 (the full width of our content area) and then multiply it by 100. The result is 20, meaning to give our site elasticity and allow it to be responsive we would define the width of our navigation column to 20%, rather than 200 px.

For a good example of a site with flexible dimensions, look no further than the page you’re on. Try decreasing the width of the page by dragging your browser window in and see how the main content area resizes itself to adapt to the new dimensions.

Along with setting your structured elements to be flexible in size, it’s also important to make your text a dynamic attribute as well.  This is accomplished much like the height and width, but rather than using a percentage sign to define your font size, or the “px” abbreviation for defining a specific pixel size, you define it as em.

Em simply stands for the letter “M”, which is the widest letter in the font and is a dynamic font measurement.  Meaning a site that uses % to define the height and width of elements, paired with font that is defined in em’s and media queries that select appropriate image sizes and content to be displayed, the result will be a fluid, responsive website.

...
more →
StevenGardner says: Love the post. I want to run an idea past you all. My idea is to serve up relevant image sizes, quality and website features...

The XREF table for MySQL

The XREF, or cross reference table, is a database table that links records together. These tables are very good for normalization in your database. I almost always use an xref when I need an many to many relationship.

Usually XREF tables have only two columns with no Primary Key. That’s right, the two columns together make them unique. They are both Foreign Keys to other tables. A real life example of this would be in any standard CRM. Let’s go over this example right now.

Many CRM’s could have a table to store notes, and a table to store accounts. If you have one user managing many accounts, they may need to put the same note for all accounts they are managing. To connect these notes to the accounts we will use an xref table.

Create a schema called ‘test_db’. Now create our accounts and notes table:

CREATE TABLE `test_db`.`accounts` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(45) NOT NULL , `phone` VARCHAR(24) NULL , `fax` VARCHAR(24) NULL , PRIMARY KEY (`id`) , UNIQUE INDEX `id_UNIQUE` (`id` ASC) ) ENGINE = InnoDB; CREATE TABLE `test_db`.`notes` ( `id` INT NOT NULL AUTO_INCREMENT , `subject` VARCHAR(45) NOT NULL , `body` VARCHAR(256) NOT NULL , PRIMARY KEY (`id`) , UNIQUE INDEX `id_UNIQUE` (`id` ASC) ) ENGINE = InnoDB;

These tables should be created first, so that the ID’s in them actually exist when we create the foreign keys in our XREF table. We are going to name the XREF table account_notes_xref. This is preference, but really good practice, as it is a single account’s note’s. The notes will be displayed on the account so the account owns the notes.

You could also get away with account_notes, but for sake of the title, we will add xref to it. This also makes things easier to spot when looking through the database. So let’s make the table:

CREATE TABLE `test_db`.`account_notes_xref` ( `account_id` INT NOT NULL , `note_id` INT NOT NULL , PRIMARY KEY (`account_id`, `note_id`) , INDEX `acx_account_id` (`account_id` ASC) , INDEX `acx_note_id` (`note_id` ASC) , CONSTRAINT `acx_account_id` FOREIGN KEY (`account_id` ) REFERENCES `test_db`.`accounts` (`id` ) ON DELETE CASCADE ON UPDATE NO ACTION, CONSTRAINT `acx_note_id`...
more →
Disqus_eric says: "I almost always use an xref when I need an many to many relationship" This implies you can do a many-to-many w/out an xref. ...

The Usefulness of the document.createElement()

The new HTML5 Markup Language has introduced several new element features not available in HTML4, for example elements like header, section, nav, footer, aside, and article.

Where these new tags will work in Opera, Safari, Chrome or Firefox they will not function in Internet Explorer (version 8 and earlier). The problem is that due to the way parsing works in IE, these elements are not recognized properly.

This tutorial explains how to get HTML5 tags to work in IE8 and its earlier releases.

It is possible to get HTML5 tags working in IE8 and earlier version by including the document.createElement() JavaScript code in the head of the HTML document. The basic idea is that by using document.createElement(tagName) to create each of the unrecognized elements, the parser in IE then recognizes those elements and parses them correctly. The following code shows the syntax for using the document.createElement.

document.createElement(“header” ); document.createElement(“footer” ); document.createElement(“section”); document.createElement(“aside” ); document.createElement(“nav” ); document.createElement(“article”);

This script means that, in the case of IE8 and earlier versions, scripting should be enabled in order to display HTML5 sectioning and headings elements properly. If not, they will not be displayed so as a precaution let’s add an explicit element to our code. (The element encloses content that should be displayed when a script is not executed. This content is also displayed in browsers that do not support the SCRIPT or in browsers which are configured not to run scripts).

Our noscript code will state the following: “ Please Note: This browser does not support HTML5, some elements are simulated using JavaScript. Enable JavaScript in order to display this page. ” and when added to the document.createElement script appears as shown below.

document.createElement(“header” ); document.createElement(“footer” ); document.createElement(“section”); document.createElement(“aside” ); document.createElement(“nav” ); document.createElement(“article”);

Please Note: This browser does not support HTML5, some elements are simulated using JavaScript. Enable JavaScript in order to display this page.

It is advisable to specify any element new to HTML5 as “block” in your CSS file otherwise declare them as inline so all browsers, including IE8 and earlier versions will handle them properly as shown below:

header ,nav ,section ,article ,aside ,footer ,hgroup { display: block; }

The document.createElement not only can be used to get HTML5 elements to function properly in IE8 and earlier browsers, but also as a means of checking for support of an element. To see how this is accomplished let’s check for support for the HTML5 canvas element.

Canvas provides an object that is used for drawing, rendering, and manipulating images and graphics on a document. The canvas object provides the surface on which to apply graphics and images. The actual drawing is done using the CanvasRenderingContext2D object, which provides the properties and methods that are used to create and manipulate graphics on a canvas object. Using the document.createElement() the JavaScript code would be written as follows:

var test_canvas = document.createElement(“canvas”) // canvas element var canvascheck=(test_canvas.getContext)? true : false //check if object supports getContext() method alert(canvascheck) //alerts true if browser supports...
more →

Designing a Clean Website Part 2: The Layout

Last week we discussed how important navigation is to a website and how developing an interactive navigation system will help give a clean, minimalist website a bit of character and make it feel modern and current. 

It’s too easy to make a clean website look dated and as though it were developed in the 90’s, so by injecting modern user interfacing techniques that are popular today you’re able to put the viewer at ease and reassure them that the content is fresh and up to date.

We’ll pick up where we left off last time and begin by setting up the basic HTML for our page layout.  Since we’re going to use a PHP include we’re going to have to save our homepage as index.php, rather than index.html. 

While I’m at it, I’m going to include a logo image in my header and put my PHP include in to pull the navigation in to the homepage. For the logo I’m just using a basic version of Developer Drive’s logo, and I’ve simply named it “logo.jpg” and placed it inside a sub-directory named “images”. 

You will also notice that I gave my <body> tag an id of “homePage”, we’ll explain why once we move on to our CSS file.  My code looks as follows.

<!DOCTYPE html> <html> <head> <title>Creating a clean website</title> <link rel="stylesheet" href="mainStyle.css" type="text/css" media="screen" charset="utf-8"/> </head> <body id="homePage"> <header><img src="images/logo.jpg" alt="header" /></header> <nav> <?php include ('navigation.php') ?> </nav> </body> </html>

Now that we’ve got our header and navigation in place, let’s add a <section> tag under our <nav> tag and drop a main image inside of it.  My HTML now looks like this:

<!DOCTYPE html> <html> <head> <title>Creating a clean website</title> <link rel="stylesheet" href="mainStyle.css" type="text/css" media="screen" charset="utf-8"/> </head> <body id="homePage"> <header><img src="images/logo.jpg" alt="header" /></header> <nav> <?php...
more →
Nick says: not having demos is a deal-breaker... just turned me off from this site entirely.

PHP User Survey Part V: Administration Layer

In the last piece on our PHP online user poll, we look at the administrative service and how the site supervisor enters, deletes and manages the poll data.

The first poll administrative page checks if the administrator is logged in. You can choose from Session variables or Cookies to check the site administrator login status.

Once the application has confirmed the identity of the site administrator, the page lists the available polls.

The first step is to use the class methods and variables in the class.polls.php file:

<?php require_once("class.polls.php");

The next steps include instantiating the poll object and retrieving the poll data:

// instantiate polls class $oPolls = new polls; // get polls and poll count $aPolls = $oPolls->getPolls("created_dt desc", $iCursor); $iCnt = $oPolls->getPollsCount();

We create an array to hold and display the data from the polls table in the database:

// check for polls if (count($aPolls)) { // build page data array $i = 0; while ($i < count($aPolls)) { $aData[$i]["Id"] = $aPolls[$i]["Poll Id"]; $aData[$i]["Name"] = $aPolls[$i]["Question"]; $aData[$i]["Status"] = $aPolls[$i]["Status"]; $aData[$i]["Created"] =$aPolls[$i]["Created Date"]; ++$i; } }

For a given poll ID number, we can delete, activate or deactivate a selected poll:

// check for id if ($id) { // assign poll id $oPolls->setPollId($id); // check operation type if (!strcmp($op, "del")) { // try delete poll and redirect $oPolls->deletePoll(); header("Location: ".SELF); } elseif (!strcmp($op, "act")) { // try activate poll and redirect $oPolls->activatePoll();...
more →
Logo Design Contest says: Good to read about administration concept which makes an incredible changes in the environment of reputable firms.