500,000 Strong

While not quite as exciting as Reddit’s billions served announcement, Switch On The Code did pass a milestone we’ve been anxiously awaiting – 500,000 pageviews!

500,000 analytics screenshot

We started looking at ways to improve our performance and I think we’ll be ditching our dedicated server and moving into the cloud. This will give us a lot more freedom in terms of scalability and reliability.

We’ve also been tossing around some new design ideas that will eventually be implemented as part of our migration to Drupal 7.

Richard Key (a.k.a The Hairiest) has been brought on as a permanent member and will be contributing lots more tutorials.

Hopefully Switch On The Code and continue this momentum and I look forward to 1 million pageviews!

jQuery Tutorial – Creating an Autocomplete Input Textbox

With jQuery 1.8 came a brand new widget – the autocomplete input field. If used correctly, like in the case of Google’s search suggestions, autocomplete can provide a major boost in productivity. Today’s tutorial is going to demonstrate how to build and populate one of these autocomplete inputs. We’re going to make two identical examples that get their data from two different sources – one will be client-side and the other will be server-side using PHP.

The example dataset will include all of the presidents of the United States. As you begin typing, the input field will automatically popup with suggestions that match your query. Feel free to play with the example below. Some good examples would be “George Washington” or “Abraham Lincoln”.

Client Side

The first example we’ll build today will be entirely client-side. This is by far the easiest approach to take, but obviously the least powerful. The jQuery demo page for autocomplete has a very nice example that we’re basically going to replicate with different data. Let’s start with the html.

<html>
  <link type="text/css" rel="stylesheet" media="all"
       href="jquery-ui-1.8.9.custom.css" />
  <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
  <script type="text/javascript" src="jquery-ui-1.8.9.custom.min.js"></script>
  <script type="text/javascript" src="presidents.js"></script>
  <body>
    <label for="presidentsClientInput">Select President (client-side): </label>
    <input id="presidentsClientInput" />
  </body>
</html>

Most of the code here is just getting jQuery included. The important part is the label and the input field. The input needs to have an id so we can reference it later and turn it into an autocomplete field.

Let’s jump into the javascript now – the source of presidents.js. The first thing we need is a datasource, which should be a simple array of values. jQuery does the work of iterating through these values to find the ones that match the text already in the input field.

$(function() {
        var presidents = [
                "George Washington",
                "John Adams",
                "Thomas Jefferson",
                "James Madison",
                "James Monroe",
                "John Quincy Adams",
                "Andrew Jackson",
                "Martin Van Buren",
                "William Henry Harrison",
                "John Tyler",
                "James Knox Polk",
                "Zachary Taylor",
                "Millard Fillmore",
                "Franklin Pierce",
                "James Buchanan",
                "Abraham Lincoln",
                "Andrew Johnson",
                "Ulysses Simpson Grant",
                "Rutherford Birchard Hayes",
                "James Abram Garfield",
                "Chester Alan Arthur",
                "Grover Cleveland",
                "Benjamin Harrison",
                "Grover Cleveland",
                "William McKinley",
                "Theodore Roosevelt",
                "William Howard Taft",
                "Woodrow Wilson",
                "Warren Gamaliel Harding",
                "Calvin Coolidge",
                "Herbert Clark Hoover",
                "Franklin Delano Roosevelt",
                "Harry S. Truman",
                "Dwight David Eisenhower",
                "John Fitzgerald Kennedy",
                "Lyndon Baines Johnson",
                "Richard Milhous Nixon",
                "Gerald Rudolph Ford",
                "James Earl Carter, Jr.",
                "Ronald Wilson Reagan",
                "George Herbert Walker Bush",
                "William Jefferson Clinton",
                "George Walker Bush",
                "Barack Hussein Obama"
        ];
});

Once we’ve got a datasource, it’s time to tell jQuery to turn our input field into an autocomplete input field.

$("#presidentsClientInput").autocomplete( { source: presidents });

We get the element with the id of “presidentsClientInput” and use the autocomplete function to convert it into an autocomplete field. The source property, in this case, points to our array of presidents. That’s all there is to it, the client-side autocomplete input field is done.

Server Side

Instructing the autocomplete field to get its data from a server is a little more complicated, but still not too bad. The first thing we need to do is add the field to our HTML and javascript.

<html>
  <link type="text/css" rel="stylesheet" media="all"
       href="jquery-ui-1.8.9.custom.css" />
  <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
  <script type="text/javascript" src="jquery-ui-1.8.9.custom.min.js"></script>
  <script type="text/javascript" src="presidents.js"></script>
  <body>
    <label for="presidentsClientInput">Select President (client-side): </label>
    <input id="presidentsClientInput" />
    <br />
    <label for="presidentsServerInput">Select President (server-side): </label>
    <input id="presidentsServerInput" />
  </body>
</html>
$("#presidentsClientInput").autocomplete( { source: presidents });
$("#presidentsServerInput").autocomplete( { source: "presidents.php" });

All I did was add a new label and input with a different id. I then added another line to the presidents.js file to setup the new input as an autocomplete field. This time, instead of setting the source to a local array, I set it to a string, which means jQuery will use this as a callback URL. It will automatically append a GET argument called “term” with the value of what’s in the input field. So, in this case, my php file will be called as “presidents.php?term=George”.

Everything for the client is now complete. It’s time to move on to the PHP file. Just like with the javascript, the first thing we need is the datasource.

<?php

$searchTerm = $_GET[‘term’];

$presidents = array(
  "George Washington",
  "John Adams",
  "Thomas Jefferson",
  "James Madison",
  "James Monroe",
  "John Quincy Adams",
  "Andrew Jackson",
  "Martin Van Buren",
  "William Henry Harrison",
  "John Tyler",
  "James Knox Polk",
  "Zachary Taylor",
  "Millard Fillmore",
  "Franklin Pierce",
  "James Buchanan",
  "Abraham Lincoln",
  "Andrew Johnson",
  "Ulysses Simpson Grant",
  "Rutherford Birchard Hayes",
  "James Abram Garfield",
  "Chester Alan Arthur",
  "Grover Cleveland",
  "Benjamin Harrison",
  "Grover Cleveland",
  "William McKinley",
  "Theodore Roosevelt",
  "William Howard Taft",
  "Woodrow Wilson",
  "Warren Gamaliel Harding",
  "Calvin Coolidge",
  "Herbert Clark Hoover",
  "Franklin Delano Roosevelt",
  "Harry S. Truman",
  "Dwight David Eisenhower",
  "John Fitzgerald Kennedy",
  "Lyndon Baines Johnson",
  "Richard Milhous Nixon",
  "Gerald Rudolph Ford",
  "James Earl Carter, Jr.",
  "Ronald Wilson Reagan",
  "George Herbert Walker Bush",
  "William Jefferson Clinton",
  "George Walker Bush",
  "Barack Hussein Obama"
);
?>

I immediately get the search term out of the GET arguments and then declare an array of presidents. Most applications will probably use some sort of database, but for clarity and simplicity, I went with a basic array.

Next we need to search the array for names that contain the text entered by the user, json encode the results, and return it back to the client.

function filter($president) {
  global $searchTerm;
  return stripos($president, $searchTerm) !== false;
}

print(json_encode(array_values(array_filter($presidents, "filter"))));

I use PHP’s array_filter function to filter the array of presidents. This function takes a callback that will be invoked on each element. If the callback returns true, the item will be added to the filtered array. To decide whether or not an item should be added to the filtered array I used stripos, which looks for an occurrence of a string using a case-insensitive compare.

The array_filter function creates an array with keys that are the index in the original array. The autocomplete field does not know how to use an array like that, so I use array_values to strip out the keys. The last thing I do is encode the array as json and print it.

That’s all there is to it for a fully functional server-side autocomplete input field. Hopefully you can use this as a starting point for some much more complicated and interesting scenarios. I didn’t show it here, but the autocomplete widget supports a more powerful callback that essentially gives you full control over how the results are returned. No matter what your system looks like, jQuery’s autocomplete widget should be able to accommodate it.

That does it for this tutorial. If you’ve got any questions feel free to leave them below or check out the forums.

Use jQuery Mobile to Build a Native Android News Reader App: Part 3

In Part 1 of this tutorial series, we introduced our sample application, described the page flow, and discussed how to construct the pages in the application via jQuery Mobile. In Part 2, we completed the implementation of our web application. In this final part, we will migrate the web application into a native Android application. […]

Read More

Android User Interface Design: Frame Layouts

Frame layouts are one of the simplest layout types used to organize controls within the user interface of an Android application. Understanding layouts is important for good Android application design. In this tutorial, you learn all about frame layouts, which are primarily used to organize individual or overlapping view controls on the screen. When used […]

Read More

How to Blow Stuff Up With the Corona SDK Physics Engine: Part 2

Welcome to part two of the How to Blow Stuff up With the Corona SDK tutorial series. In this tutorial, we will be enhancing our demo app from part I by allowing the user to place an actual bomb graphic on the screen with a time-delayed explosion. We will aslo modify the explosion effect to […]

Read More

Use jQuery Mobile to Build a Native Android News Reader App: Part 2

In Part 1 of this tutorial series, we introduced our sample application, described the page flow, and discussed how to construct the pages in the application via jQuery Mobile. In Part 2, we will complete the implementation of our web application. Application Startup Having reviewed the basic page structure in Part 1, let us now […]

Read More

Developing RESTful iOS Apps with RestKit

RestKit is a powerful library that simplifies interacting with web services for iOS applications. In this article, written by RestKit creator and Two Toasters CTO Blake Watters, we will take a quick tour of RestKit’s feature set, get familiar with the core concepts presented by the library, and then explore some code samples to get […]

Read More

Best of jQuery Content Sliders

Create a Slick and Accessible Slideshow Using jQuery

jquery slider 9 Best of jQuery Content Sliders
In this in-depth web development tutorial, you’ll learn how to create a usable and web accessible slideshow widget for your site using HTML, CSS, and JavaScript (jQuery).
Live Demo


Create Featured Content Slider Using jQuery UI

jquery slider 1 Best of jQuery Content Sliders
This tutorial that teaches you how to Create Featured Content Slider Using jQuery UI.
Live Demo


Create an Image Rotator with Description (CSS/jQuery)

jquery slider 8 Best of jQuery Content Sliders
An image rotator is one great way to display portfolio pieces, eCommerce product images, or even as an image gallery. Although there are many great plugins already, this tutorial will help you understand how the image rotator works and helps you create your own from scratch.
Live Demo


Build a Content Slider with jQuery

jquery slider 2 Best of jQuery Content Sliders
This tutorial that teaches you how to Build a Content Slider with jQuery.
Live Demo


Easy Slider

jquery slider 3 Best of jQuery Content Sliders
The Easiest jQuery Plugin For Sliding Images and Content.
Live Demo


AnythingSlider jQuery Plugin

jquery slider 4 Best of jQuery Content Sliders
On CSS-Tricks they have created a number of different sliders. A “featured content” slider, a “start/stop slider”, and “moving boxes”. Each of them had some cool interesting feature that I needed to build at the time. All were well-received, This new AnythingSlider is an attempt at bringing together the functionality of all of those previous sliders and adding new features. In other words, to create a really “full featured” slider that could be widely useful.
Live Demo


Start/Stop Slider

jquery slider 5 Best of jQuery Content Sliders
Another good content slider from CSS-Tricks. with diffrent style of slider animation.
Live Demo


WordPress Theme using JQuery s3Slider

jquery slider 6 Best of jQuery Content Sliders
Creating Featured Slider in WordPress Theme using JQuery s3Slider
Live Demo


BarackSlideshow

jquery slider 7 Best of jQuery Content Sliders
BarackSlideshow is a very tiny and lightweight slideshow script, that takes the power of MorphList to enhance visualization and navigation of the images.
Live Demo



Supersized

jquery slider 11 Best of jQuery Content Sliders
Full screen slideshow jQuery plugin
Live Demo


Popeye

jquery slider 12 Best of jQuery Content Sliders
jQuery.popeye is an advanced image gallery script built on the JavaScript library jQuery. Use it to save space when displaying a collection of images and offer your users a nice and elegant way to show a big version of your images without leaving the page flow.
Live Demo


How to Switch work in iPhone

This is the very simple example. In this example we will see how to Switch function worked.

Step 1: Create a View base application using template. Give the application name “SwitchON”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: xpand classes and notice Interface Builder created the SwitchONViewController class for you. Expand Resources and notice the template generated a separate nib, SwitchONViewController.xib, for the “SwitchON”.

Step 4: Open the SwitchONViewController.h file and make the following changes in the file.

#import <UIKit/UIKit.h>

@interface SwitchONViewController : UIViewController {

IBOutlet        UILabel *display;
IBOutlet UISwitch *switch1;
       
}

@property (nonatomic,retain) UISwitch *switch1;

@property (nonatomic,retain) UILabel *display;

(IBAction)messagedisplay:(id)sender;

Step 5: Double click the SwitchONViewController.xib file and open it to the Interface Builder. Now first drag the switch from the library and place it to the view window and drag the label from the library and place it to the view window. Select the label from the view window and bring up attribute inspector, give the Text name “Please Switch me OFF!” . Select the switch from the view window and bring up Connection Inspector, connect Value Changed to the File’s Owner icon and select messagedisplay:, Connect File’s Owner icon to the switch and select switch1. Now save it close it and go back to the Xcode.

Step 6: In the SwitchONViewController.m file make the following changes.

(IBAction)messagedisplay:(id)sender
{
        NSString *message1 = [[NSString alloc] initWithFormat:@"Please switch me OFF!"];
        NSString *message2 = [[NSString alloc] initWithFormat:@"Please switch me ON!"];
       
        if (switch1.on){               
                display.text = @"Please switch me OFF!";
                [message1 release];
        }
        else {  
                display.text = message2;
                [message2 release];
        }
       
}

Step 7: Now compile and run the application in the simulator.

You can Download SourceCode from here SwitchON

ImageRotate using touch in iPhone

This is the ImageRotate example . In this example we will see how to image rotate anywhere of the screen using touch.

Step 1: Create a View base application using template. Give the application name “ImageMove_iPhone”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: Xpand classes and notice Interface Builder created the ImageMove_iPhoneViewController class for you. Expand Resources and notice the template generated a separate nib,ImageMove_iPhoneViewController.xib, for the “ImageMove_iPhone”.

Step 4: We need to add UIView class in the project. Select Classes -> Add -> New File -> Cocoa Touch Class -> Objective C class -> select UIView from the Subclass of. Give the file name “ImageMove”.

Step 5: We have added one resource in the Resources folder. Give the name of the resource “11.jpg”,”feder.jpg”.

Step 6: In the ImageMove.h file, we specified the superclass as a UIImageView. So make the following changes in the file:

#import <UIKit/UIKit.h>

@interface ImageMove : UIImageView {

}

Step 7: Open the ImageMov.m file , make the following changes in the file.

(id) initWithImage:(UIImage *)image {
        if (self = [super initWithImage:image]) {
                [self setUserInteractionEnabled:YES];
                [self setMultipleTouchEnabled:YES];
        } return self;
}

(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
        if ([touches count] == 1) {
                CGPoint newTouch = [[touches anyObject] locationInView:[self superview]];
                CGPoint lastTouch = [[touches anyObject] previousLocationInView: [self superview]];
               
                float xDif = newTouch.x lastTouch.x;
                float yDif = newTouch.y lastTouch.y;
                CGAffineTransform translate = CGAffineTransformMakeTranslation(xDif, yDif);
                [self setTransform: CGAffineTransformConcat([self transform], translate)];
        }
       
       
}

Step 8: In the the ImageMove_iPhoneViewController.h file we have import “ImageMove.h” file.

Step 9: Open the mageMove_iPhoneViewController.m file, we create ImageView and make it visible. So make the following changes in the file.

(void)viewDidLoad {
    [super viewDidLoad];
       
        ImageMove* imageMove = [[ImageMove alloc] initWithImage:[UIImage imageNamed:@"11.jpg"]];
        [imageMove setFrame:CGRectMake(110, 60, [imageMove frame].size.width,[imageMove frame].size.height)];
        [[self view] addSubview:imageMove];
        [imageMove release];
       
               
        ImageMove* imageMove1 = [[ImageMove alloc] initWithImage:[UIImage imageNamed:@"feder.jpg"]];
        [imageMove1 setFrame:CGRectMake(110, 200, [imageMove1 frame].size.width,[imageMove1 frame].size.height)];
        [[self view] addSubview:imageMove1];
        [imageMove1 release];
       

}

Step 10: Now compile and run the application in the Simulator.

You can Download SourceCode from here ImageMove_iPhone