20 Mac Apps You’ll Use Every Day: Editor’s Choice

20 Mac Apps You’ll Use Every Day: Editor’s Choice

Mac app round-ups are a dime a dozen across the web. However, there’s one problem when you’re offered 100+ to choose from: you won’t use half of them. That’s why I’ve decided to streamline the process and provide twenty of my most highly recommended Mac apps, tailored for web designers and developers. While not every app relates specifically to development, they’re all essential in your every day workflow.


1. VMWare Fusion

While online services, like Browsershots and Adobe Browserlab are definitely helpful, there really is no substitute for testing your new website in Internet Explorer itself. When you must do so, assuming you only own a Mac, your best option is to use a virtual machine. Again, there are a variety to choose from; however, my preference is VMWare Fusion.

“With VMware Fusion, run the most demanding Mac and Windows applications side-by-side at maximum speeds without rebooting. With over 50 new features and a new ultra-fast Migration Assistant for Windows, it’s never been easier to run Windows on your Mac.”


2. The Hit List

As I run Nettuts, ThemeForest, and CodeCanyon, it’s essential that I find the best possible tools for plotting out each day. I’ve used the huge majority of the offerings, ranging from Things, to GQueues, to TeuxDeux. Truthfully, they’re all fantastic, each offering something unique. While, lately, I’ve found myself using GQueues for my day-to-day tasks, I always find myself coming back to The Hit List when preparing a new project.

“The Hit List is a simple, yet sophisticated application to manage the daily chaos of your modern life. Based on the simple concept of making lists, The Hit List lets you plan, forget, then act when the time is right.”

Alternative


3. TextMate

Perhaps the most obvious choice of the bunch, but, nonetheless, it’s an essential tool for every developer. When considering sheer speed, nothing compares to TextMate.

“TextMate brings Apple’s approach to operating systems into the world of text editors. By bridging UNIX underpinnings and GUI, TextMate cherry-picks the best of both worlds to the benefit of expert scripters and novice users alike.”


4. TextExpander

If you find yourself rewriting the same lines of code, the same paragraphs, even the same signature over and over each day, you’re doing it wrong. How many hours each year would you save, simply by turning an eight second repetitive typing task into a keystroke? Especially in my particular circumstance, TextExpander is 100% a necessity.

“Save time and effort with TextExpander! Whether it’s a simple email signature or several paragraphs of a standard response, you’ll love how easy it is to use TextExpander to avoid typing the same thing over and over.”


5. Snippely

As we switch from language to language, it’s nearly impossible to remember every function for every language. This is when a code collection app becomes a huge help. Need to remember the code that you use for PHP CRUD operations? Simply save it into Snippely, and return when you need it.

While Snippely isn’t the most glamorous app, and is depressingly simple, it still gets the job done.

“Snippely is a basic text and code organizational tool. Instead of storing bits of code, quick notes, and memos in text files all over your hard drive, this application will let you save and organize “snippets” in one convenient location. A snippet is a collection of one or more pieces of code and notes. Snippets are stored in groups for organization and quick retrieval.”


6. Skitch

Skitch is easily one of my favorite, and most helpful apps for Mac. Further, it’s one of those apps that you truthfully can’t find on the PC, for some reason. If I need to point out a strange issue on ThemeForest to my boss, I can use Skitch to select a portion of the page as a snapshot, then add some arrows and text describing the problem on the image, and upload it Skitch’s server for hosting – all within a time span of about twenty seconds.

“Skitch.com is a webservice that works hand in hand with our application Skitch to give you 1-click uploading of images for fast and fun image sharing.”


7. Sequel Pro

When working with MySQL, PHPMyAdmin definitely gets the job done, but it sure is ugly! Sequel Pro is the beautiful, and free alternative!

“Sequel Pro is a fast, easy-to-use Mac database management application for working with MySQL databases.”


8. Google Quick Launch

While QuickSilver has generally has been the quick-launch app tool of choice, Google has a fantastic alternative that’s even better, called Quick Search Box. In addition to loading applications with only a keystroke, you also have the ability to perform Google searches, and search your Gmail account.

“With Google Quick Search Box you can search for information from just about anywhere. As you type, suggestions will appear that match your query, ranging from applications and local files on your computer, to web search and navigational suggestions, to items from your browser history and contacts.”

Alternative


9. Photoshop

Obvious choice? Most definitely. However, that’s only a testament to its importance. In addition to Gmail, Photoshop is open on my computer at all times. And while free alternative like Gimp might be helpful, I honestly question your dedication to web design if you’re not using the industry standard.

“Adobe® Photoshop® CS4 software provides improved access to its unrivaled power through a more intuitive user experience, greater editing freedom, and significant productivity enhancements.”

Alternative


10. Notify

For those brief moments when your email client isn’t open, Notify makes for a fantastic alternative. A tiny icon is placed at the top of your desktop, displaying the number of items in your inbox. It also notifies you (obviously) when new emails arrive, and allows you to read, respond to, and delete them with ease.

“Do you access your email in a browser? Then you’ll love Notify. Notify is an awesome email notifier for Mac OS X. It fits seamlessly into your menubar, only vying for your attention when you have new mail. Notify supports mutliple accounts, including Gmail/Google Apps, MobileMe, and Rackspace Email.”


11. Mamp

For PHP/MySQL development, Mamp makes setting up a local web server on your computer laughably simple.

“The one-click solution for setting up your web server.”


12. Forklift

Forklift is one of my more recent discoveries this year. I often find myself trying to drag files from one folder to another. Using Mac’s finder, this can be a bit of a pain. Also, every day, I’m transferring files to Envato’s S3 accounts. Forklift makes this process as easy as it can possibly be. While not free, I highly recommend that you pick this one up.

Alternative

“Forklift is a powerful file manager and ferociously fast FTP client clothed in a clean and versatile UI that offers the combination of absolute simplicity and raw power expected from a well-executed Mac software”


13. Dropzone

Dropzone is a helpful little tool that automates the process of common tasks. For example, when you download an app, you must then double click on the app, install it, and finally drag the app to your Applications folder. It’s not a huge time waster, though every thirty seconds matters! With Dropzone, you drag your file into the app, and it automatically performs these tasks for you.

This is only one of many operations that Dropzone performs. Be sure to check it out!

“The Swiss army knife of drag-and-drop for the Mac. Dropzone makes it faster and easier to get things done on your Mac.”


14. Coda

Perhaps side-by-side with TextMate, Coda is one of the best code editors (if not the best) that the Mac has to offer. Especially when you find yourself editing files stored on your server, there’s no easier tool.

“So, we code web sites by hand. And one day, it hit us: our web workflow was wonky. We’d have our text editor open, with Transmit open to save files to the server. We’d be previewing in Safari, adjusting SQL in a Terminal, using a CSS editor and reading references on the web. “This could be easier,” we declared. “And much cooler.”


15. Echofon

I’m on Twitter every day, for better or worse. Surprisingly, the app that I most prefer flies right under the radar. Maybe I’m missing something, but it, along with its iPhone companion app, does everything that I could possibly require (excluding scheduled tweets): multiple accounts, search, etc. P.S. If you’re not following us on Twitter, do so before I cut you!

“Echofon for mac suits those who do intense Twittering, and those who want to something that stays out of their way until they need it. The interface contracts and expands to your ideal size, and the drawer will show you details only when you need it.”


16. Cinch

There’s no denying that Windows 7 is a vast improvement over its predecessor. One of my favorite (though simple) new features is the ability to lock windows to different sides of the screen. I’m sure you’ve seen the commercial of the mechanic advertising this feature on TV. Drag one window to the left-side of the screen, and it automatically expands/contracts to take up 50% width of the monitor. You can then do the same to another window, to quickly allow for a side-by-side view. While the Mac doesn’t natively support this, you can use an app called Cinch to mimic this functionality. I use it every day!

“Cinch gives you simple, mouse-driven window management by defining the left, right, and top edges of your screen as ‘hot zones’. Drag a window until the mouse cursor enters one of these zones then drop the window to have it cinch into place.”


17. 1Password

According to 1Password, I have over fifty different accounts and passwords on the web. Assuming we’re smart and use unique passwords for each account, it’s nearly impossible to remember every username and password without tearing out your hair. With 1Password, you simply store your login credentials, and use Command + Backslash to automatically login. This single app has saved me dozens and dozens of hours over the last year.

“1Password can create strong, unique passwords for you, remember them, and restore them, all directly in your web browser.”

Alternative


18. Dropbox

Ever needed to quickly transfer a file from your laptop over to your desktop? It’s a bit of a drag, isn’t it? What did you do, email yourself with the file? Even burn a CD to transfer it? How old-fashioned is that!? Instead, use DropBox to make the process as simple as it can possibly be. While not specifically a Mac “app,” it’s definitely essential to your work-flow.

“Dropbox allows you to sync your files online and across your computers automatically.”


19. WebStorm

I discovered this new code editor last month, and am very excited about it. Be sure to watch my three minute video above for a quick overview of some of my favorite features.

“WebStorm is an Integrated Development Environments for web programming, providing a unique user experience for editing HTML, CSS, JavaScript, XMl, as well as for working with VCS and SQL.”


Conclusion

While there are countless more offerings available around the web, the items listed above are what I use every single day. Did I miss any? Have any recommendations?



Celebrating the Launch of GIFtuts+

Celebrating the Launch of GIFtuts+

Today we’re pleased to introduce the newest member of the Tuts+ family: GIFtuts+. We’ll be publishing tutorials and video training on creating gorgeous animated GIFs in Photoshop, Ulead GIF Animator and Microangelo. If you’ve ever wanted to freely learn how to create ornamental animated GIFs and impressive navigational graphics for Web Pages, now is the time to start! Hit the jump to learn all about GIFtuts+ and check out the newest site in the Tuts+ Network family.

We care about GIFs

Happy artist.

Creating GIFs is a topic that we often get asked about. Whenever we’ve published a tutorial on creating GIFs on Psdtuts+, like our Animated Snowman Tutorial, it’s been very popular. We thought it was about time we gave this in-demand but under-served aspect of design education its own dedicated Tuts+ site!

Giftuts+ Logo

Here’s a sneak peek of what the site will have to offer in the coming weeks:

  • How to Create Hellish Animated Flaming Skulls
  • How to Make a Slick ‘Under Construction’ Sign
  • Make a Blood-spattering Stick-figure Animation

We want to take a moment to thank our team of developers and designers for all their hard work on the new site: Derek, Fred and Ryan, thanks guys!

Cowboy on computer.

Enough talk… it’s time to get moving and visit GIFtuts+!

ENTER
ENTER

And… our newest Envato marketplace

    Pointing hand.
  • Tying in with the launch of our newest Tuts+ site we’re also debuting a new Envato marketplace to a select group of Beta testers. If you’re interested in making passive income from your GIFs – meaning you make a GIF once, then sell it many times – we have an exciting announcement for you.

GifHole is looking for talented animated/static GIF artists to help set the standard for a new online GIF marketplace. Envato (the makers of Tuts+) are developing this site for all those who are looking for quality GIF stock and those who want to become authors in this field and earn money by selling their work online, again and again.

Giftuts+ Logo

GifHole will complement the existing Envato marketplaces: ActiveDen, AudioJungle, ThemeForest, VideoHive and GraphicRiver.

Flaming Skull



Generating a Particle System with JavaScript: New Premium Tutorial

Generating a Particle System with JavaScript: New Premium Tutorial

If you’ve ever seen a fireworks effect, created in Flash, I’ll show you how to reproduce the effect using pure JavaScript in this week’s Premium tutorial! Why let the Flash developers have all the fun? Help give back to Nettuts+ by becoming a Premium member.


Join Net Premium

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!



How to Create an Infinite Scrolling Web Gallery

How to Create an Infinite Scrolling Web Gallery

When working my way through a web gallery, I find it annoying when I must change pages; so in today’s tutorial, we will learn how to create an auto-generating, one-page, infinite scrolling gallery with PHP and AJAX. Let’s get started!


Step 1: Project Outline

We’ll begin with a normal gallery page that has a container for our images, and we’ll monitor the scroll position by calling a JavaScript function at a quick interval. Each time the scroll bar is near the bottom, we’ll make an AJAX request to an external PHP file, which returns a list of image names. Now, all we’ll need to do is add these images to our container, thus modifying the page height moving the scroll position higher.


Step 2: HTML Markup

We’ll work with a very basic setup: a header and the container for our images. The thumbnails will be grouped in sets of three rows, each will contain a link, referencing the full size image. After each group, we will add some text showing the total number of displayed images, and a link to the top of the page.

<body>
	<div id="header">Web Gallery | Infinite Scroll</div>
	<div id="container">
		<a href="img/Achievements.jpg"><img src="thumb/Achievements.jpg" /></a>
		<a href="img/Bw.jpg"><img src="thumb/Bw.jpg" /></a>
		<a href="img/Camera.jpg"><img src="thumb/Camera.jpg" /></a>
		<a href="img/Cat-Dog.jpg"><img src="thumb/Cat-Dog.jpg" /></a>
		<a href="img/CREATIV.jpg"><img src="thumb/CREATIV.jpg" /></a>
		<a href="img/creativ2.jpg"><img src="thumb/creativ2.jpg" /></a>
		<a href="img/Earth.jpg"><img src="thumb/Earth.jpg" /></a>
		<a href="img/Endless.jpg"><img src="thumb/Endless.jpg" /></a>
		<a href="img/EndlesSlights.jpg"><img src="thumb/EndlesSlights.jpg" /></a>    

		<p>9 Images Displayed | <a href="#header">top</a></p>
	    <hr />
	</div>
</body>

Step 3: CSS

The CSS is also quite basic. First, we define the page colors and positioning for the header and paragraphs.

body{
	background:#222;
	color:#666;
}
#header{
	font-family:Arial, Helvetica, sans-serif;
	font-size:24px;
	font-weight:bold;
	text-align:left;
	text-indent:35px;
	margin: 0 auto;
	width:800px;
	margin-bottom:10px;
}
hr{
	margin: 20px;
	border:none;
	border-top: 1px solid #111;
	border-bottom: 1px solid #333;
}
p{
	color:#444;
	text-align:left;
	font-size:10px;
	margin-left: 20px;
	margin-bottom: -10px;
}
a{
	color:#444;
}

Step 4

Then, for the container and images, I used a bit of CSS3 to add round corners and shadows. Don’t forget "-moz-box-shadow" and "-moz-border-radius" for Firefox and "-webkit-box-shadow" and "-webkit-border-radius" for Chrome and Safari.

#container{
	margin: 0 auto;
	width:800px;
	border:1px solid #333;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
	font-family:Verdana, Geneva, sans-serif;
	text-align:center;
}
img{
	border:10px solid #444;
	-moz-border-radius: 5px;
	-webkit-border-radius: 10px;
	margin: 15px;
}
img:hover{
	border-color:#555;
	-moz-box-shadow: 0px 0px 15px #111;
	-webkit-box-shadow: 0px 0px 15px #111;
}

Step 5: PHP Script

This is going to be very short. We need to call the PHP script with the index of the next image we need as a parameter. First of all, we have to retrieve all the available image names from a directory and save them into an array. I organized my images in two folders: "thumb" and "img" which contain the thumbnails and actual images, respectively. Note that the thumbnails must have the exact same name as their corresponding full size images.

<?php

$dir = "thumb";
if(is_dir($dir)){
	if($dd = opendir($dir)){
		while (($f = readdir($dd)) !== false)
			if($f != "." && $f != "..")
				$files[] = $f;
	closedir($dd);
	} 

We define a variable for the directory we want to get the image names from, test if it exists, and if we can open it, read all the file names from it. When reading an entire folder, we will always get two extra elements we may not want: "." – this stands for the current directory, and ".." – this stands for the parent directory. To compensate, we have to test if the element read is different from these two, then we can safely add it to our array.

$files[] = $f;

As a note, when adding an element to an array and not specifying the position to be placed in, it will always push the element to the end of the array.


Step 6

Now we have to build our response text. We are going to send back to the JavaScript a single string containing all the necessary file names separated by a semi-colon.

	$n = $_GET["n"];
	$response = "";

We get the URL parameter for the index of the next image we need, and we initialize our response text.

	for($i = $n; $i<$n+9; $i++)
		$response = $response.$files[$i%count($files)].';';
	echo $response;
}
?>

As I said before, the images will be grouped in sets of three rows, each containing three images, so we only need nine images to return the file names for a group. We start at the index we got as parameter, $n, and go until $n+9. At each increment, we add our image name followed by ";" to the response text. Here is a little tricky part. We won’t have an infinite number of images; so in order to create the effect of an "infinite" gallery which never ends, each time the index of the next image is greater that the total number of images, we must start over from the beginning. This is done by applying the "modulo" or "%" function between the index and the total number of images.

	$i%count($files)

As a result, we get the remainder of the division between these two elements. For example, if the index "$i" is "50" and the number of images "count($files)" is "45" the result will be "5". As well, if "$i" is "50" and "count($files)" is "65", the result will be "50". Finally, we have to send back our response text.


Step 7

Here is the complete PHP script. Just place your completed code within a new .php file.

<?php

	$dir = "thumb";
	if(is_dir($dir)){
		if($dd = opendir($dir)){
			while (($f = readdir($dd)) !== false)
				if($f != "." && $f != "..")
					$files[] = $f;
			closedir($dd);
		} 

	$n = $_GET["n"];
	$response = "";
		for($i = $n; $i<$n+9; $i++){
			$response = $response.$files[$i%count($files)].';';
		}
		echo $response;
	}
?>

Step 8: JavaScript

As usual, first we define some variables we will need later on.

var contentHeight = 800;
var pageHeight = document.documentElement.clientHeight;
var scrollPosition;
var n = 10;
var xmlhttp;

In order to determine weather the scroll bar is near the bottom of the page, we need three variables:

  • "contentHeight" – the height of the initial gallery
  • "pageHeight" – the height of the visible page in the browser
  • "scrollPosition" – the position of the scroll bar measured from the top

Lastly, we need a variable for the next image index (which we are going to send to the PHP script), and a variable for the Ajax request object.


Step 9

We need to define a function that will add the images to our HTML container.

function putImages(){
	if (xmlhttp.readyState==4){
    	if(xmlhttp.responseText){

A request object goes through different states as the request is made, each of which has a numerical value associated. The one we are interested in is the final state, when the request is complete and the value is "4". We first test if the request is in this state, and then check to see if we received a response.


Step 10

If both conditions are fulfilled, we have to tokenize the response text. This means we have to separate the file names into an array. Remember that in the PHP script we returned a single string with the names separated by semi-colons. Here is an example: Achievements.jpg;Bw.jpg;Camera.jpg;Cat-Dog.jpg;CREATIV.jpg;creativ2.jpg;Earth.jpg;Endless.jpg;EndlesSlights.jpg;

var resp = xmlhttp.responseText.replace("\r\n", "");
var files = resp.split(";");

There is a bit of a problem we have to deal with first; the response text may have at the beginning a new line character which we do not want. This is easily fixed with the "replace" function, that takes two parameters: "\r\n" – the new line character, and "" – empty string that will replace all occurrences of the first parameter. Now all we have to do is to split the string by our delimiter ";".


Step 11

Next, we have to add the images to our container.

            var j = 0;
            for(i=0; i<files.length; i++){
                if(files[i] != ""){
                    document.getElementById("container").innerHTML += '<a href="img/'+files[i]+'"><img src="thumb/'+files[i]+'" /></a>';
                    j++;

                    if(j == 3 || j == 6)
                        document.getElementById("container").innerHTML += '';
                    else if(j == 9){
                        document.getElementById("container").innerHTML += '<p>'+(n-1)+" Images Displayed | <a href='#header'>top</a></p><hr />";
                        j = 0;
                    }
                }
            }

For every element in our array, we check if it isn’t an empty string, and add the thumbnail with the link on it. We have to keep a counter "j" in order to separate the images in rows. After every third and sixth thumbnail added, we create a new line, and after nine thumbnails added we put the text showing the total number of displayed images and a link to the top of the page.


Step 12

Here is the complete function.

function putImages(){
	if (xmlhttp.readyState==4){
    	if(xmlhttp.responseText){
			var resp = xmlhttp.responseText.replace("\r\n", "");
			var files = resp.split(";");

            var j = 0;
            for(i=0; i<files.length; i++){
                if(files[i] != ""){
                    document.getElementById("container").innerHTML += '<a href="img/'+files[i]+'"><img src="thumb/'+files[i]+'" /></a>';

                    j++;
                    if(j == 3 || j == 6)
                        document.getElementById("container").innerHTML += '';
                    else if(j == 9){
                        document.getElementById("container").innerHTML += '<p>'+(n-1)+" Images Displayed | <a href='#header'>top</a></p><hr />";
                        j = 0;
                    }
                }
            }
		}
	}
}

Step 13

Now we are going to define the function that will check if the scroll position is getting near the bottom, and makes the request to the server.

function scroll(){

	if(navigator.appName == "Microsoft Internet Explorer")
		scrollPosition = document.documentElement.scrollTop;
	else
		scrollPosition = window.pageYOffset;

First, we have to find the position of the scroll bar. Internet Explorer does this a bit differently, so we have to determine what browser the client is using, then just store the value in the variable we defined earlier.


Step 14

	if((contentHeight - pageHeight - scrollPosition) < 500){

Now we check to see if we are about to reach the end of our gallery – if the part of the page visible in the browser is below the bottom 500px of the entire page. This isn’t an exact value, you may use a different one if you find it suitable. If this condition is true, we can continue on and add new images.


Step 15: Creating the XMLHttpRequest Object

We are ready to make the XMLHttpRequest object and send it. Again, for Internet Explorer the definition is a bit different, so we must compensate for this as well.

	if(window.XMLHttpRequest)
			//Firefox, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		else
			if(window.ActiveXObject)
            	//Internet Explorer
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			else
				alert ("Bummer! Your browser does not support XMLHTTP!");

Step 16

Before sending the request, we have to specify the PHP script name on the server and insert the parameters we want to give it.

	var url="getImages.php?n="+n;

This is a simple text variable representing the URL of the page.


Step 17

It’s time to send the request.

		xmlhttp.open("GET",url,true);
		xmlhttp.send();

The URL is set by calling the "open" method. The second parameter is the important one, this being the script’s URL. After doing so, all we need is to send it. This will run the PHP script and put in "xmlhttp.responseText" the return value of it.


Step 18

The final step is to place the new content on the page by calling the function we defined earlier "putImages" and to prepare our variables for the next request.

		n += 9;
		contentHeight += 800;
		xmlhttp.onreadystatechange = putImages;
	}
}

We have nine new images in the gallery, so we increment "n" with 9, and we need to change the page height; so increment "contentHeight" with 800.


Step 19

Here is the entire JavaScript we’ve used.

<script>
var contentHeight = 800;
var pageHeight = document.documentElement.clientHeight;
var scrollPosition;
var n = 10;
var xmlhttp;

function putImages(){

	if (xmlhttp.readyState==4)
	  {
		  if(xmlhttp.responseText){
			 var resp = xmlhttp.responseText.replace("\r\n", "");
			 var files = resp.split(";");
			  var j = 0;
			  for(i=0; i<files.length; i++){
				  if(files[i] != ""){
					 document.getElementById("container").innerHTML += '<a href="img/'+files[i]+'"><img src="thumb/'+files[i]+'" /></a>';
					 j++;

					 if(j == 3 || j == 6)
						  document.getElementById("container").innerHTML += '';
					  else if(j == 9){
						  document.getElementById("container").innerHTML += '<p>'+(n-1)+" Images Displayed | <a href='#header'>top</a></p><hr />";
						  j = 0;
					  }
				  }
			  }
		  }
	  }
}

function scroll(){

	if(navigator.appName == "Microsoft Internet Explorer")
		scrollPosition = document.documentElement.scrollTop;
	else
		scrollPosition = window.pageYOffset;		

	if((contentHeight - pageHeight - scrollPosition) < 500){

		if(window.XMLHttpRequest)
			xmlhttp = new XMLHttpRequest();
		else
			if(window.ActiveXObject)
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			else
				alert ("Bummer! Your browser does not support XMLHTTP!");		  

		var url="getImages.php?n="+n;

		xmlhttp.open("GET",url,true);
		xmlhttp.send();

		n += 9;
		xmlhttp.onreadystatechange=putImages;
		contentHeight += 800;
	}
}



Step 20

The final thing that we must do is run the JavaScript at a specified interval.

<body onload="setInterval('scroll();', 250);">

Just set up the "onload" property of the "body" tag, and set its value to the "setInterval" function. This will run the "scroll" function every quarter of a second. Again, you may change this time value, but I found that it’s optimal for what we need.


Finished!

We are done! I hope you found this tutorial to be of help and useful. Please leave a message in the comment section below, should you need further assistance or advice.



How to Create an Infinite Scroll Web Gallery

How to Create an Infinite Scroll Web Gallery

When working my way through a web gallery, I find it annoying when I must change pages; so in today’s tutorial, we will learn how to create an auto-generating, one-page, infinite scrolling gallery with PHP and AJAX. Let’s get started!


Step 1: Project Outline

We’ll begin with a normal gallery page that has a container for our images, and we’ll monitor the scroll position by calling a JavaScript function at a quick interval. Each time the scroll bar is near the bottom, we’ll make an AJAX request to an external PHP file, which returns a list of image names. Now, all we’ll need to do is add these images to our container, thus modifying the page height moving the scroll position higher.


Step 2: HTML Markup

We’ll work with a very basic setup: a header and the container for our images. The thumbnails will be grouped in sets of three rows, each will contain a link, referencing the full size image. After each group, we will add some text showing the total number of displayed images, and a link to the top of the page.

<body>
	<div id="header">Web Gallery | Infinite Scroll</div>
	<div id="container">
		<a href="img/Achievements.jpg"><img src="thumb/Achievements.jpg" /></a>
		<a href="img/Bw.jpg"><img src="thumb/Bw.jpg" /></a>
		<a href="img/Camera.jpg"><img src="thumb/Camera.jpg" /></a>
		<a href="img/Cat-Dog.jpg"><img src="thumb/Cat-Dog.jpg" /></a>
		<a href="img/CREATIV.jpg"><img src="thumb/CREATIV.jpg" /></a>
		<a href="img/creativ2.jpg"><img src="thumb/creativ2.jpg" /></a>
		<a href="img/Earth.jpg"><img src="thumb/Earth.jpg" /></a>
		<a href="img/Endless.jpg"><img src="thumb/Endless.jpg" /></a>
		<a href="img/EndlesSlights.jpg"><img src="thumb/EndlesSlights.jpg" /></a>    

		<p>9 Images Displayed | <a href="#header">top</a></p>
	    <hr />
	</div>
</body>

Step 3: CSS

The CSS is also quite basic. First, we define the page colors and positioning for the header and paragraphs.

body{
	background:#222;
	color:#666;
}
#header{
	font-family:Arial, Helvetica, sans-serif;
	font-size:24px;
	font-weight:bold;
	text-align:left;
	text-indent:35px;
	margin: 0 auto;
	width:800px;
	margin-bottom:10px;
}
hr{
	margin: 20px;
	border:none;
	border-top: 1px solid #111;
	border-bottom: 1px solid #333;
}
p{
	color:#444;
	text-align:left;
	font-size:10px;
	margin-left: 20px;
	margin-bottom: -10px;
}
a{
	color:#444;
}

Step 4

Then, for the container and images, I used a bit of CSS3 to add round corners and shadows. Don’t forget "-moz-box-shadow" and "-moz-border-radius" for Firefox and "-webkit-box-shadow" and "-webkit-border-radius" for Chrome and Safari.

#container{
	margin: 0 auto;
	width:800px;
	border:1px solid #333;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
	font-family:Verdana, Geneva, sans-serif;
	text-align:center;
}
img{
	border:10px solid #444;
	-moz-border-radius: 5px;
	-webkit-border-radius: 10px;
	margin: 15px;
}
img:hover{
	border-color:#555;
	-moz-box-shadow: 0px 0px 15px #111;
	-webkit-box-shadow: 0px 0px 15px #111;
}

Step 5: PHP Script

This is going to be very short. We need to call the PHP script with the index of the next image we need as a parameter. First of all, we have to retrieve all the available image names from a directory and save them into an array. I organized my images in two folders: "thumb" and "img" which contain the thumbnails and actual images, respectively. Note that the thumbnails must have the exact same name as their corresponding full size images.

<?php

$dir = "thumb";
if(is_dir($dir)){
	if($dd = opendir($dir)){
		while (($f = readdir($dd)) !== false)
			if($f != "." && $f != "..")
				$files[] = $f;
	closedir($dd);
	} 

We define a variable for the directory we want to get the image names from, test if it exists, and if we can open it, read all the file names from it. When reading an entire folder, we will always get two extra elements we may not want: "." – this stands for the current directory, and ".." – this stands for the parent directory. To compensate, we have to test if the element read is different from these two, then we can safely add it to our array.

$files[] = $f;

As a note, when adding an element to an array and not specifying the position to be placed in, it will always push the element to the end of the array.


Step 6

Now we have to build our response text. We are going to send back to the JavaScript a single string containing all the necessary file names separated by a semi-colon.

	$n = $_GET["n"];
	$response = "";

We get the URL parameter for the index of the next image we need, and we initialize our response text.

	for($i = $n; $i<$n+9; $i++)
		$response = $response.$files[$i%count($files)].';';
	echo $response;
}
?>

As I said before, the images will be grouped in sets of three rows, each containing three images, so we only need nine images to return the file names for a group. We start at the index we got as parameter, $n, and go until $n+9. At each increment, we add our image name followed by ";" to the response text. Here is a little tricky part. We won’t have an infinite number of images; so in order to create the effect of an "infinite" gallery which never ends, each time the index of the next image is greater that the total number of images, we must start over from the beginning. This is done by applying the "modulo" or "%" function between the index and the total number of images.

	$i%count($files)

As a result, we get the remainder of the division between these two elements. For example, if the index "$i" is "50" and the number of images "count($files)" is "45" the result will be "5". As well, if "$i" is "50" and "count($files)" is "65", the result will be "50". Finally, we have to send back our response text.


Step 7

Here is the complete PHP script. Just place your completed code within a new .php file.

<?php

	$dir = "thumb";
	if(is_dir($dir)){
		if($dd = opendir($dir)){
			while (($f = readdir($dd)) !== false)
				if($f != "." && $f != "..")
					$files[] = $f;
			closedir($dd);
		} 

	$n = $_GET["n"];
	$response = "";
		for($i = $n; $i<$n+9; $i++){
			$response = $response.$files[$i%count($files)].';';
		}
		echo $response;
	}
?>

Step 8: JavaScript

As usual, first we define some variables we will need later on.

var contentHeight = 800;
var pageHeight = document.documentElement.clientHeight;
var scrollPosition;
var n = 10;
var xmlhttp;

In order to determine weather the scroll bar is near the bottom of the page, we need three variables:

  • "contentHeight" – the height of the initial gallery
  • "pageHeight" – the height of the visible page in the browser
  • "scrollPosition" – the position of the scroll bar measured from the top

Lastly, we need a variable for the next image index (which we are going to send to the PHP script), and a variable for the Ajax request object.


Step 9

We need to define a function that will add the images to our HTML container.

function putImages(){
	if (xmlhttp.readyState==4){
    	if(xmlhttp.responseText){

A request object goes through different states as the request is made, each of which has a numerical value associated. The one we are interested in is the final state, when the request is complete and the value is "4". We first test if the request is in this state, and then check to see if we received a response.


Step 10

If both conditions are fulfilled, we have to tokenize the response text. This means we have to separate the file names into an array. Remember that in the PHP script we returned a single string with the names separated by semi-colons. Here is an example: Achievements.jpg;Bw.jpg;Camera.jpg;Cat-Dog.jpg;CREATIV.jpg;creativ2.jpg;Earth.jpg;Endless.jpg;EndlesSlights.jpg;

var resp = xmlhttp.responseText.replace("\r\n", "");
var files = resp.split(";");

There is a bit of a problem we have to deal with first; the response text may have at the beginning a new line character which we do not want. This is easily fixed with the "replace" function, that takes two parameters: "\r\n" – the new line character, and "" – empty string that will replace all occurrences of the first parameter. Now all we have to do is to split the string by our delimiter ";".


Step 11

Next, we have to add the images to our container.

            var j = 0;
            for(i=0; i<files.length; i++){
                if(files[i] != ""){
                    document.getElementById("container").innerHTML += '<a href="img/'+files[i]+'"><img src="thumb/'+files[i]+'" /></a>';
                    j++;

                    if(j == 3 || j == 6)
                        document.getElementById("container").innerHTML += '';
                    else if(j == 9){
                        document.getElementById("container").innerHTML += '<p>'+(n-1)+" Images Displayed | <a href='#header'>top</a></p><hr />";
                        j = 0;
                    }
                }
            }

For every element in our array, we check if it isn’t an empty string, and add the thumbnail with the link on it. We have to keep a counter "j" in order to separate the images in rows. After every third and sixth thumbnail added, we create a new line, and after nine thumbnails added we put the text showing the total number of displayed images and a link to the top of the page.


Step 12

Here is the complete function.

function putImages(){
	if (xmlhttp.readyState==4){
    	if(xmlhttp.responseText){
			var resp = xmlhttp.responseText.replace("\r\n", "");
			var files = resp.split(";");

            var j = 0;
            for(i=0; i<files.length; i++){
                if(files[i] != ""){
                    document.getElementById("container").innerHTML += '<a href="img/'+files[i]+'"><img src="thumb/'+files[i]+'" /></a>';

                    j++;
                    if(j == 3 || j == 6)
                        document.getElementById("container").innerHTML += '';
                    else if(j == 9){
                        document.getElementById("container").innerHTML += '<p>'+(n-1)+" Images Displayed | <a href='#header'>top</a></p><hr />";
                        j = 0;
                    }
                }
            }
		}
	}
}

Step 13

Now we are going to define the function that will check if the scroll position is getting near the bottom, and makes the request to the server.

function scroll(){

	if(navigator.appName == "Microsoft Internet Explorer")
		scrollPosition = document.documentElement.scrollTop;
	else
		scrollPosition = window.pageYOffset;

First, we have to find the position of the scroll bar. Internet Explorer does this a bit differently, so we have to determine what browser the client is using, then just store the value in the variable we defined earlier.


Step 14

	if((contentHeight - pageHeight - scrollPosition) < 500){

Now we check to see if we are about to reach the end of our gallery – if the part of the page visible in the browser is below the bottom 500px of the entire page. This isn’t an exact value, you may use a different one if you find it suitable. If this condition is true, we can continue on and add new images.


Step 15: Creating the XMLHttpRequest Object

We are ready to make the XMLHttpRequest object and send it. Again, for Internet Explorer the definition is a bit different, so we must compensate for this as well.

	if(window.XMLHttpRequest)
			//Firefox, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		else
			if(window.ActiveXObject)
            	//Internet Explorer
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			else
				alert ("Bummer! Your browser does not support XMLHTTP!");

Step 16

Before sending the request, we have to specify the PHP script name on the server and insert the parameters we want to give it.

	var url="getImages.php?n="+n;

This is a simple text variable representing the URL of the page.


Step 17

It’s time to send the request.

		xmlhttp.open("GET",url,true);
		xmlhttp.send();

The URL is set by calling the "open" method. The second parameter is the important one, this being the script’s URL. After doing so, all we need is to send it. This will run the PHP script and put in "xmlhttp.responseText" the return value of it.


Step 18

The final step is to place the new content on the page by calling the function we defined earlier "putImages" and to prepare our variables for the next request.

		n += 9;
		contentHeight += 800;
		xmlhttp.onreadystatechange = putImages;
	}
}

We have nine new images in the gallery, so we increment "n" with 9, and we need to change the page height; so increment "contentHeight" with 800.


Step 19

Here is the entire JavaScript we’ve used.

<script>
var contentHeight = 800;
var pageHeight = document.documentElement.clientHeight;
var scrollPosition;
var n = 10;
var xmlhttp;

function putImages(){

	if (xmlhttp.readyState==4)
	  {
		  if(xmlhttp.responseText){
			 var resp = xmlhttp.responseText.replace("\r\n", "");
			 var files = resp.split(";");
			  var j = 0;
			  for(i=0; i<files.length; i++){
				  if(files[i] != ""){
					 document.getElementById("container").innerHTML += '<a href="img/'+files[i]+'"><img src="thumb/'+files[i]+'" /></a>';
					 j++;

					 if(j == 3 || j == 6)
						  document.getElementById("container").innerHTML += '';
					  else if(j == 9){
						  document.getElementById("container").innerHTML += '<p>'+(n-1)+" Images Displayed | <a href='#header'>top</a></p><hr />";
						  j = 0;
					  }
				  }
			  }
		  }
	  }
}

function scroll(){

	if(navigator.appName == "Microsoft Internet Explorer")
		scrollPosition = document.documentElement.scrollTop;
	else
		scrollPosition = window.pageYOffset;		

	if((contentHeight - pageHeight - scrollPosition) < 500){

		if(window.XMLHttpRequest)
			xmlhttp = new XMLHttpRequest();
		else
			if(window.ActiveXObject)
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			else
				alert ("Bummer! Your browser does not support XMLHTTP!");		  

		var url="getImages.php?n="+n;

		xmlhttp.open("GET",url,true);
		xmlhttp.send();

		n += 9;
		xmlhttp.onreadystatechange=putImages;
		contentHeight += 800;
	}
}



Step 20

The final thing that we must do is run the JavaScript at a specified interval.

<body onload="setInterval('scroll();', 250);">

Just set up the "onload" property of the "body" tag, and set its value to the "setInterval" function. This will run the "scroll" function every quarter of a second. Again, you may change this time value, but I found that it’s optimal for what we need.


Finished!

We are done! I hope you found this tutorial to be of help and useful. Please leave a message in the comment section below, should you need further assistance or advice.



10+ regular expressions for efficient web development

10+ regular expressions for efficient web development

Validate an URL

Is a particular url valid? The following regexp will let you know.

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \?=.-]*)*\/?$/

Source: http://snipplr.com/view/19502/validate-a-url/

Validate US phone number

This regexp will verify that a US phone number is valid.

/^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/

Source: http://snippets.dzone.com/posts/show/597

Test if a password is strong

Weak passwords are one of the quickest ways to get hacked. The following regexp will make sure that:

  • Passwords will contain at least (1) upper case letter
  • Passwords will contain at least (1) lower case letter
  • Passwords will contain at least (1) number or special character
  • Passwords will contain at least (8) characters in length
  • Password maximum length should not be arbitrarily limited
(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$

Source: http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=297

Get code within <?php and ?>

If for some reason you need to grab all the code contained within the <?php and ?> tags, this regexp will do the job:

<\?[php]*([^\?>]*)\?>

Source: http://snipplr.com/view/12845/get-all-the-php-code-between/

Match tel: urls

In a recent post, I showed you how you can use iPhone special link prfixes to automatically call someone.
This regular expression will match those tel: urls.

^tel:((?:\+[\d().-]*\d[\d().-]*|[0-9A-F*#().-]*[0-9A-F*#][0-9A-F*#().-]*(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*'().-]|%[\dA-F]{2})+)?)*;phone-context=(?:\+[\d().-]*\d[\d().-]*|(?:[a-z0-9]\.|[a-z0-9][a-z0-9-]*[a-z0-9]\.)*(?:[a-z]|[a-z][a-z0-9-]*[a-z0-9])))(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*'().-]|%[\dA-F]{2})+)?)*(?:,(?:\+[\d().-]*\d[\d().-]*|[0-9A-F*#().-]*[0-9A-F*#][0-9A-F*#().-]*(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*'().-]|%[\dA-F]{2})+)?)*;phone-context=\+[\d().-]*\d[\d().-]*)(?:;[a-z\d-]+(?:=(?:[a-z\d\[\]\/:&+$_!~*'().-]|%[\dA-F]{2})+)?)*)*)$

Source: http://tools.ietf.org/html/rfc3966#section-3

Validate US zip code

When building a registration form, it is common to ask the user’s zip code. As forms are often boring, there’s a strong chance that the user will try to register false data. This regular expression will make sure he entered a valid American zip code.

^[0-9]{5}(-[0-9]{4})?$

Source: http://reusablecode.blogspot.com/2008/08/isvalidzipcode.html

Validate Canadian postal code

This regexp is very similar to the previous one, but it will match Canadian postal codes instead.

^[ABCEGHJ-NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$

Source: http://reusablecode.blogspot.com/2008/08/isvalidpostalcode.html

Grab unclosed img tags

As you probably know, the xhtml standard requires all tags to be properly closed. This regular expression will search for unclosed img tags. It could be easily modified to grab any other unclosed html tags.

<img([^>]+)(\s*[^\/])>

Source: http://snipplr.com/view/6632/grab-any-unclosed-xhtml-img-tags/

Find all CSS attributes

This regexp will find CSS attributes, such as background:red; or padding-left:25px;.

\s(?[a-zA-Z-]+)\s[:]{1}\s*(?[a-zA-Z0-9\s.#]+)[;]{1}

Source: http://snipplr.com/view/17903/find-css-attributes/

Validate an IBAN

I have recently worked on a banking application and this one was definitely a life-saver. It will verify that the given IBAN is valid.

[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}

Source: http://snipplr.com/view/15322/iban-regex-all-ibans/

Validate a BIC code

Another one very useful for any banking application or website: This regexp will validate a BIC code.

([a-zA-Z]{4}[a-zA-Z]{2}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?)

Source: http://snipplr.com/view/15320/bic-bank-identifier-code-regex/

If you’re interested in regular expressions, make sure you have read our “15 PHP regular expression for developers” post.

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

10+ regular expressions for efficient web development

Free Ticket to the jQuery Conference in San Francisco

Free Ticket to the jQuery Conference in San Francisco

On April 24-25, I’ll be attending the jQuery conference in San Francisco, and I hope many of you will as well! With speakers like John Resig, Steve Souders, Rey Bango, and other highly respected members from the jQuery team, it’s sure to be a fantastic event! Now, if you haven’t purchased your ticket just yet, the team has given me one ticket to give away for free.

“The San Francisco Bay Area conference is the second of four events planned by the jQuery Project in 2010. The first was the jQuery14 event, and additional conferences are being planned in Europe and on the East Coast for later this year.”

jQuery Conference

Hosted at Microsoft

“The San Francisco Bay Area conference will be held at the Microsoft Silicon Valley Research Center in Mountain View, California. This venue is the largest that the project has worked with to date (Harvard Law School in ’07, the MIT Stata Center in ’08 and Microsoft New England Research Center in ’09) and we expect to sell out very quickly.”


How to Enter

The winner will receive one complimentary ticket to attend the jQuery conference. He or she will still be responsible for accommodations, and/or travel expenses, per usual. If you’re in or near the Bay area of San Francisco, and would LOVE to attend, leave a comment of no more than three sentences telling us why.
If you aren’t selected to win the free ticket, admission is only $199, which is quite cheap when you consider the level of knowledge that you’ll gain as a result of attending. I’ll be attending, and will hope to see you there!

Get a Superb Hosting

Diving into the Twitter API

Diving into the Twitter API

Twitter’s astonishing growth is rivaled only by its intuitive, developer friendly API. In this second part of the series, we are going to learn more about Twitter’s API and how to work with it.

Too much abstraction is never a good thing.

In this Web 2.0 era, web applications which have an easy to use, intuitive API have a distinct advantage as it lets developers exploit and build for the platform and thus capture more users. As we move towards the social web and mashups, a good API is not a nice addition anymore: it is downright necessary. And remember, too much abstraction is never a good thing. While there are a number of API kits out there to simplify working with the API in question, wouldn’t it be cool to know what is actually going on under the hood? Wouldn’t it be exciting to deconstruct the actual voodoo going on between the kit and the API? Yeah, I thought so!


Before we Begin

For each functionality, I am going to show you how to achieve it in two ways: the first using a server side language, PHP in this case, and the second using only a client side language, JavaScript. Each implementation will function separately and achieve the required functionality. Feel free to mix and match these solutions to create a hybrid. The JavaScript examples will use JSON as the format for the payload while for the PHP example I’ve chosen XML.


Twitter API Basics

The first thing you need to know about the Twitter API is that it is RESTful. To cut the jargon, it means you access appropriate URLs using GET or POST requests to modify, request or manipulate the data exposed by the API.

There are three separate Twitter APIs actually.

  • The normal REST based API
  • The Search API
  • The Stream API

Each of these APIs have their own distinct set of functionality, quirks, advantages and disadvantages.

REST API

The REST methods constitute the core of the Twitter API, and are written by the devs at Twitter itself. It allows other developers to access and manipulate all of Twitter’s main data. You’d use this API to do all the usual stuff you’d want to do with Twitter including retrieving statuses, updating statuses, showing a user’s timeline, sending direct messages and so on.

Search API

The search API is actually the brainchild of the guys over at Summize Inc, a company which Twitter acquired for its API. The search API lets you look beyond you and your followers. You need this API if you are looking to view trending topics and so on.

Stream API

Finally we have the stream API. This API lets developers sample huge amounts of real time data. Since this API is only available to approved users, we aren’t going to go over this today.


Authentication and all that Boohockey

Public data can be freely accessed without an API key. When requesting private data and/or user specific data, Twitter requires authentication. You can authenticate with Twitter using either of two methods.

Basic Authentication

This is the default method of authentication Twitter initially launched with and still uses. In this method, you pass the user name and password as Bse64 encoded strings in the header of the HTTP request. A sample GET request would look like so.

GET /somefolder/index.html HTTP/1.1
Host: net.tutsplus.com
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

Looks a tiny bit complicated doesn’t it? Let me explain. The first two lines are part of a standard GET request. The third line is where all of magic happens. We make sure the server knows we are using basic auth to authenticate with it, and then pass in the base 64 encoded string of username:password as the value. The server can then decode the credentials, check them and provide access if everything matches.

Twitter supporting basic auth is probably one of the reasons it got so big since it let a multitude of developers develop for the platform since the barrier of entry is relatively low. Basic auth is sufficient to retrieve all parts of the API.

OAuth

Twitter started supporting OAuth in the second quarter of 2009. Users using OAuth enabled application need not divulge their passwords to the program and can also delegate control to the program with multiple levels of access. However, we’ll not look at Twitter’s OAuth implementation today. OAuth and implementing its workflow is a rather complex topic and requires an article of its own. I’d rather skip over OAuth for this article rather than throw out some half baked explanations and writing code based on those explanations.


Caution

“Twitter only lets you make a predefined number of calls to its API.”

Before we delve in to the coding part, I need to make one thing absolutely clear: Twitter only lets you make a predefined number of calls to its API. The REST API’s limit is 150 for an hour, while the search API’s limit is undisclosed as of now. For authenticated calls, the call is deducted from the authenticating user’s limit, while for unauthenticated calls it is deducted from the calling IP’s quota.

Remember, when developing an application, make sure you either cache the information or respect the limit and stay within it. If you think the preset limit is insufficient for your application, you could always apply for white listing.


The Most Common Tasks

Instead of looking at a number of methods you probably won’t ever use, I’ve decided to show you how to do the three most common tasks.

  • Retrieving your status
  • Updating your status
  • Searching Twitter

I think this is a proper subset of the API which directly covers what the API is most used for without spreading itself too thin by covering a ton of methods. With that out of the way, let’s get started!


Retrieving your Status

The first functionality we are going to look at is displaying a user’s status. This is the most popular use of the API if a web developer wants to display a given user’s status without resorting to a Twitter badge.

PHP Method #1: Direct Retrieval

<?php
$response = new SimpleXMLElement('http://twitter.com/users/show/userid.xml',NULL,TRUE);
echo $response->status->text.' - '.date("g:i: A D, F jS Y",strtotime($response->status->created_at));
?>

The first method utilizes PHP. It’s a relatively simple method where we just grab the user specific XML file, and then parse it to display the current status.

We first convert the XML file into an object so we can easily traverse through it using the SimpleXML extension which comes standard with PHP. Now that the object has been created, we just find the status node, and print out the status text and creation time.

Remember, this only displays the current status of the user. If you want a list of recent updates, see below.

PHP Method #2: cURL

cURL is a command line tool and comes enabled on most hosted servers. To quote Wikipedia:

In computing, cURL functions as a command-line tool for transferring files with URL syntax.

It is a library designed to allow users to connect to different types of servers using different protocols. Using cURL is the method of choice for all the Twitter libraries out there and we’ll be using the same.

<?php

     $username = 'xxx';
	 $password = 'yyy';
     $curlhandle = curl_init();
	 curl_setopt($curlhandle, CURLOPT_URL, "http://twitter.com/statuses/user_timeline.xml");
	 curl_setopt($curlhandle, CURLOPT_USERPWD, $username.':'.$password);
     curl_setopt($curlhandle, CURLOPT_RETURNTRANSFER, 1);
     $response = curl_exec($curlhandle);
     curl_close($curlhandle);
     $xmlobj = new SimpleXMLElement($response); 

	 foreach ($xmlobj->status as $status)
	 {
    echo $status->text.'<br /> by'.$status->user->screen_name.' at '
    .date("g:i: A D, F jS Y",strtotime($status->created_at)).'<br /> <br /> ' ;
    }
?> 

Let me explain. First, we assign our username and password to separate variables to be used later. I then set the URL to the value mentioned above. Since the method requires authentication, we send in our username and password.

Next, we execute our call and store the response in a seperate variable. We then convert it into a valid XML object and then parse the data, printing out the status and when it was posted.

I’ve formatted the data and time to look the way I want. If you want fancy dates and times like 3 hours ago or 12 days ago, you either need to look for a snippet or code one yourselves. Twitter only returns normally formatted data and time.

You’ll receive an output, similar to this:

I am stupid. Didn't use an IDE and missed a comma wasting 110 minutes.
Remind me not to try debugging when I am sleepy or tired.
at 6:01: PM Fri, February 14th 2010

Flood of traffic. :O I must have budgeted for this many visitors. Argh! Hope nothing breaks.
at 8:51: PM Thu, February 13th 2010

JavaScript

Using JavaScript to display your status is the most elegant way to go forward since you can load it asynchronously after the page has loaded, which means, even if Twitter is downm or being tardy, your site functions the same.

We are going to use jQuery’s ajax method to do all our dirty work today.

 $.ajax({
    		url : "http://twitter.com/statuses/user_timeline/userid.json?callback=?",
			dataType : "json",
			timeout:15000,

			success : function(data)
			{
				  $("#data").html("Data successfully obtained! <br />");
  for (i=0; i<data.length; i++)
				{
  $("#data").append("<p>" + data[i].text) +"</p>";
  $("#data").append("<p>" + data[i].created_at +"</p>");
				}
			},

			error : function()
			{
				alert("Failure!");
			},

		});

Again, a big chunk of code but, broken down, it’s simple really. We use jQuery’s lowest level AJAX function instead of the getJSON method, since the low level call seems to be more versatile.

First up, we define the URL and the datatype. We also add a callback function to the URL to circumvent the cross domain restriction on most browsers. Without this callback, our script wouldn’t run; it’d just return an error and quit.

I’ve chosen not to authenticate, because we are specifying an ID in the URL, and hence don’t need authentication – that and because basic auth is not really safe for sensitive information. You don’t want to send out your password over an insecure line.

Finally, the success function which is called when no errors are encountered. We just parse the returned JSON object and print out the text and the creation time. #data is just a container where we put all our data.

A Quick Note

This code is the template for all your methods which access data. Very minimal change is required to modify it to work with other API methods.

For the PHP example, all you’d need to do is change URL value to point to a new method, and you should be mostly done. If the method requires parameters, you just add them directly to the URL itself. Simple as that.

Same with the JavaScript example. All you’d need to do is change the URL that the methods request, and you should be done. Be sure to fetch only public data with the JavaScript method.

Remember, this code is the base for all your other methods which retrieve data. This includes methods getting your direct messages, timelines, friends, followers and mentioned tweets. Just change the url, add in a parameter as needed, and you’re all set! Easy, no?


Updating your Status

With any Twitter application you are creating, letting users update their status through it is a no-brainer. Remember, previously applications using basic auth were able to use a custom source string for all tweets sent from their application. Now, implementing OAuth is the only way you get a custom string. In short, if you want all tweets sent from your application to have a link back to your app, use OAuth. With that out of the way, let’s see the code.

PHP

<?php

    $username = 'xxx';
	 $password = 'yyy';
    $status= 'Testing out cURL with the Twitter API';
    $curlhandle = curl_init();
	 curl_setopt($curlhandle, CURLOPT_URL, "http://twitter.com/statuses/update.xml");
	 curl_setopt($curlhandle, CURLOPT_USERPWD, $username.':'.$password);
    curl_setopt($curlhandle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curlhandle, CURLOPT_POST, 1);
	 curl_setopt($curlhandle, CURLOPT_POSTFIELDS, "status=$status");
    $response = curl_exec($curlhandle);
    curl_close($curlhandle);

?>

We can use cURL just as easily to post to Twitter. The code is almost the same as before except we change the url to the appropriate one. Also, we make sure posting is enabled, and set the fields to be posted. The API method requires a status parameters, and so we set the value of the status variable to this parameter.

Do remember to make sure the text to be posted is UTF-8 encoded. Otherwise, we’d run into needless errors.

We now save the response to be used for later. In this example, I’ve chosen to do nothing. But in a practical application you’d definitely want to display a success/error message and/or display the response.

JavaScript

Posting a status update to Twitter using only JavaScript seems to be impossible right now since there is no way to pass the user’s id and password. With Flickr, those credentials are passed on as part of the POST request itself. With Twitter, this data needs to be sent in the HTTP headers, and there doesn’t seem to be a way of doing that.

Even disregarding the fact that you can’t send credentials over to the service, there is still the problem of not being able to make cross domain POST requests with the XMLHttp object. These two points make API methods which require a POST request a strict no-no with JavaScript.

In case you are interested, a successful post nets you this response.

<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<status>
  <created_at>Fri Aug 14 21:31:53 +0000 2009</created_at>
  <id>3316091255</id>
  <text>Testing out cURL with the Twitter API</text>
  <source><a href="http://apiwiki.twitter.com/" rel="nofollow">API</a></source>
  <truncated>false</truncated>

  <in_reply_to_status_id></in_reply_to_status_id>
  <in_reply_to_user_id></in_reply_to_user_id>
  <favorited>false</favorited>
  <in_reply_to_screen_name></in_reply_to_screen_name>
  <user>
    <id>18118645</id>
    <name>Tony / Siddharth</name>

    <screen_name>lordtottuu</screen_name>
    <location>India</location>
    <description>Gamer, developer, web designer, writer, geek. </description>
    <profile_image_url>http://s3.amazonaws.com/twitter_production/profile_images/300532536/NVAGSoNIpS_o5XxbmB4pl-boGheY6JBASaiLiieGIAO6JTitHnRMNJa6ktCPRMQW_normal.jpg</profile_image_url>
    <url>http://ssiddharth.com</url>
    <protected>false</protected>

  </user>

</status>

A Quick Note

The code techniques discussed above consist of the base for all your data which sends data to Twitter. This includes methods which lets you follow/unfollow someone, send direct messages, creating favorites, blocking people, and so on and so forth.

The only thing you’d need to do is change out these URLs, see whether they require extra parameters, and add them as needed. Nothing else required.


Searching Twitter

Letting users search through Twitter for information is potentially an important need of an application. For this purpose, we can use the search API to query Twitter.

PHP

<?php

    $searchstring = "Envato";
    $curlhandle = curl_init();
	curl_setopt($curlhandle, CURLOPT_URL, "http://search.twitter.com/search.json?q=$searchstring");
    curl_setopt($curlhandle, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec($curlhandle);
    curl_close($curlhandle);

    $json = json_decode($response);
	foreach ($json->results as $result)
	{
	echo $result->text;
	}

?>

The above code lets you search Twitter for tweets which reference Envato. As usual, we change the URL to point to the correct API method and proceed. Since this method is only available in either JSON or ATOM formats, I’ve chosen to go with JSON.

I’ve used PHP’s built-in json_decode function to convert it into an object so we could parse the response easily. In this example, I’ve only printed out the tweets themselves. In your applications, you’d probably want to display more. A sample response is below.

[text] => @nsethi check out http://www.envato.com/ if you want some sick tuts...I'm gonna blog about it later.
[to_user_id] => 1273919
[to_user] => nsethi
[from_user] => thinklime
[id] => 3315720513
[from_user_id] => 33020944
[iso_language_code] => en
source] => Tweetie
[profile_image_url] => http://s3.amazonaws.com/twitter_production/profile_images/201032569/idTwitter_normal.jpg
[created_at] => Fri, 14 Aug 2009 21:10:42 +0000

As you can see, a lot of info about the user and the tweet itself is available. Feel free to mix and match.

JavaScript

 $.ajax({

    		url : "http://search.twitter.com/search.json?q=somestring&callback=?",
			dataType : "json",
			timeout:15000,

			success : function(data)
			{
				  // parse data here
			},

			error : function()
			{
				alert("Failure!");
			},

		});

As usual, we use the ajax method to ping Twitter’s search service. Just as in the previous example, we’ve included a callback function to get over the cross domain restriction.

A sample response, plucked directly from Twitter, looks like so.

{"results":[

     {"text":"@twitterapi  http:\/\/tinyurl.com\/ctrefg",

     "to_user_id":396524,

     "to_user":"TwitterAPI",

     "from_user":"jkoum",

     "id":1478555574,   

     "from_user_id":1833773,

     ... truncated ...],

     "since_id":0,

     "max_id":1480307926,

     "refresh_url":"?since_id=1480307926&q=%40twitterapi",

     "results_per_page":15,

     "next_page":"?page=2&max_id=1480307926&q=%40twitterapi",

     "completed_in":0.031704,

     "page":1,

     "query":"%40twitterapi"}
}

As a side note, the search method can be used in a variety of ways really.

  • ?q=Envato – Searches for tweets containing the string Envato
  • ?q=#Envato – Searches for hashtags of Envato
  • ?phrase=Envato+marketplace – Searches for tweets containing the phrase Envato marketplace
  • ?q=from:NETTUTS – Returns all tweets from NETTUTS
  • ?q=to:NETTUTS – Returns for all tweets to NETTUTS

Why Other Methods Aren’t Covered

I’ve decided to limit myself to showing how to read from and write to a service using its API. This way, I can focus only on those specific methods. And also because most methods build on these basics. If you want to return a friend’s timeline, you’d just change the URL and parse through the response with minimal fuss.

The same occurs if you want to send a direct message to another user or mention another user. The basics of posting is still there. You just need to add in a parameter or two to make it all happen. It doesn’t make sense to cover all that when I can just explain the basics a lot more clearly.


Conclusion

I hope you’ve learned more about how to work with Twitter’s API today. As always, let me know, via the comments, if you need any help!



How to Use the jQuery UI Autocomplete Widget

How to Use the jQuery UI Autocomplete Widget

In this tutorial we’ll be looking at one of jQuery UI 1.8’s newest components – the Autocomplete widget. Auto-completing text fields can be a popular choice with visitors to your site because they make entering information much easier. They can be used on product search fields for example, or when a visitor must enter a country, or a city, or anything else that may be a choice from a common dataset. As well as being popular with visitors, the jQuery UI Autocomplete is popular with developers because it’s easy to use, powerful and flexible.

I’m not a massive fan of Facebook, I much prefer Twitter (@danwellman btw), but one Facebook feature I do like is the messaging feature which lets you send a message to a friend or friends. I like how the autocomplete is used to make selecting your friend’s names easier, and how the names are formatted once they have been selected and added to the ‘to’ field, e.g. they each have a close link in them that allows the name to be easily removed without having to select any text.

In this tutorial we’ll use the jQuery UI Autocomplete widget to replicate this aspect of Facebook’s messaging system. We won’t be looking at actually sending messages however. This is what we’re going to create:


Step 1 Getting Started

We’ll need to build a custom download of jQuery UI containing just the components we need; head over to the download builder at http://jqueryui.com/download. We’ll need to use the following core components:

  • Core
  • Widget
  • Position

We’ll also need the Autocomplete widget itself so ensure that just the above items, as well as Autocomplete, are checked in the Components section at the left. Use the default theme (UI Lightness) and ensure that version 1.8 is selected at the right.

Once downloaded, create a new folder on your computer and call it autocomplete. Then open the archive and copy the css and js folders into the new folder you just created. This will give you all of the library files required for this example including jQuery itself, so this doesn’t need to be downloaded separately.


Step 2 The Underlying HTML

Let’s look at the HTML for the <form> first of all:

<div id="formWrap">
	<form id="messageForm" action="#">
		<fieldset>
			<legend>New message form</legend>
			<span>New Message</span>
			<label id="toLabel">To:</label>
			<div id="friends" class="ui-helper-clearfix">
				<input id="to" type="text">
			</div>
			<label>Subject:</label>
			<input id="subject" name="subject" type="text">
			<label>Message:</label>
			<textarea id="message" name="message" rows="5" cols="50"></textarea>
			<button type="button" id="cancel">Cancel</button>
			<button type="submit" id="send">Send</button>
		</fieldset>
	</form>
</div>

It’s a pretty standard form; there’s an outer container <div> we can use for styling and the <input> that the Autocomplete will be attached to is also within a <div> element; we’ll style the <input> so that it’s slightly hidden, and we’ll style the <div> so that it looks like the other fields in the form. We give the container for the <input> the ui-helper-clearfix class name to make use of this utility class from jQuery UI’s CSS framework.

We’ll also need to link to the files we unpacked from the jQuery UI archive, as well as a custom stylesheet; the following files should go into the <head> of the page:

<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.8.custom.css">
<link rel="stylesheet" type="text/css" href="css/autocomplete.css">

The following files should go at the end of the <body>:

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.custom.min.js"></script>

Step 3 Styling the Form

We use a very simple, neutral theme in this example, most of which is purely as an example. Very few of the styles are required and most can be changed if necessary. The following CSS is used in the autocomplete.css style sheet (all of the jQuery UI styling is in the jquery-ui-1.8.custom.css style sheet):

#formWrap {
	padding:10px; position:absolute; float:left; background-color:#000;
	background:rgba(0,0,0,.5); -moz-border-radius:10px;
	-webkit-border-radius:10px; border-radius:10px;
}
#messageForm {
 width:326px; border:1px solid #666; background-color:#eee;
}
#messageForm fieldset {
	padding:0; margin:0; position:relative; border:none;
	background-color:#eee;
}
#messageForm legend { visibility:hidden; height:0; }
#messageForm span {
	display:block; width:326px; padding:10px 0; margin:0 0 20px;
	text-indent:20px; background-color:#bbb;
	border-bottom:1px solid #333;	font:18px Georgia, Serif; color:#fff;
}
#friends {
	width:274px; padding:3px 3px 0; margin:0 auto;
	border:1px solid #aaa; background-color:#fff; cursor:text;
}
#messageForm #to {
	width:30px; margin:0 0 2px 0; padding:0 0 3px;
	position:relative; top:0; float:left; border:none;
}
#messageForm input, #messageForm textarea {
	display:block; width:274px; padding:3px; margin:0 auto 20px;
	border:1px solid #aaa;
}
#messageForm label {
	display:block; margin:20px 0 3px; text-indent:22px;
	font:bold 11px Verdana, Sans-serif;	color:#666;
}
#messageForm #toLabel { margin-top:0; }
#messageForm button { float:right; margin:0 0 20px 0; }
#messageForm #cancel { margin-right:20px; }
#friends span {
	display:block; margin:0 3px 3px 0; padding:3px 20px 4px 8px;
	position:relative; float:left; background-color:#eee;
	border:1px solid #333; -moz-border-radius:7px;
	-webkit-border-radius:7px; border-radius:7px; color:#333;
	font:normal 11px Verdana, Sans-serif;
}
#friends span a {
	position:absolute; right:8px; top:2px; color:#666;
	font:bold 12px Verdana, Sans-serif; text-decoration:none;
}
#friends span a:hover { color:#ff0000; }
.ui-menu .ui-menu-item { white-space:nowrap; padding:0 10px 0 0; }

To give the form a nice transparent border with rounded corners we use the CSS3 RGBa rule and the -moz-border-radius, -webkit-border-radius and border-radius rules; most popular browsers now support these rules, including Firefox, Safari, Chrome and Opera. IE doesn’t support either of them, and although it can use a filter to implement rudimentary opacity, rounded corners would need to be supported through the use of images. The effectiveness of the RGBa transparency isn’t shown to its fullest in this example; but this type of form would probably be used as a floating modal overlay in a full implementation, which would sit above actual content on the page.

The container <div> around the <input> field that the Autocomplete text field will be attached to is given the same positioning and styling as the <input> elements, but the <input> within this container has its border removed so that it is hidden. We also reduce its width and float it to the left. This is so that when we add the formatted recipients to the <div> the <input> won’t overflow and increase the height of the <div> unnecessarily.

We also style the recipients, which will be added to the <div> as <span> elements containing a link. Mostly these are styled to match the basic theme and are also given rounded corners. It’s important that these elements are made block-level and also float so that they stack up correctly. We also need to override some of the Automcomplete styling provided by the jQuery UI theme we are using; the last selector simply prevents the individual suggestions in the menu breaking between words, which happens because we have made the <input> it is associated with so small.

At this stage, the form should appear like this:


Step 4 Attaching the Autocomplete

Next we need to attach the Autocomplete widget to the <input> within the <div>; to do this we can use the following script:

<script type="text/javascript">
	$(function(){

		//attach autocomplete
		$("#to").autocomplete({

			//define callback to format results
			source: function(req, add){

				//pass request to server
				$.getJSON("friends.php?callback=?", req, function(data) {

					//create array for response objects
					var suggestions = [];

					//process response
					$.each(data, function(i, val){
					suggestions.push(val.name);
				});

				//pass array to callback
				add(suggestions);
			});
		},

		//define select handler
		select: function(e, ui) {

			//create formatted friend
			var friend = ui.item.value,
				span = $("<span>").text(friend),
				a = $("<a>").addClass("remove").attr({
					href: "javascript:",
					title: "Remove " + friend
				}).text("x").appendTo(span);

				//add friend to friend div
				span.insertBefore("#to");
			},

			//define select handler
			change: function() {

				//prevent 'to' field being updated and correct position
				$("#to").val("").css("top", 2);
			}
		});
	});
</script>

The widget is attached to the <input> using the autocomplete() method. We supply an object literal as an argument to the method, which configures the source option and the select and change event callbacks.

The source option is used to tell the widget where to get the suggestions for the Autocomplete menu from. We use a function as the value of this option, which accepts two arguments; the first is the term entered into the <input>, the second is a callback function which is used to pass the suggestions back to the widget.

Within this function we use jQuery’s getJSON() method to pass the term to a server-side PHP file. The PHP file will use the term to extract matching contact names from a MySql database. We use a JSONP callback to process the data returned from the server; the callback function that is passed as the second argument to the source option expects to receive the data in an array, so we first create an empty array and then use jQuery’s each() method to process each item in the JSON array returned by the server. We simply iterate over each item in this array, and add each suggestion to our new array. Once our new array is built we pass it to the callback function for the widget to display in the menu.

We then define a handler for the Autocomplete’s custom select event; this function will be executed by the widget each time a suggestion is selected from the Autocomplete menu. This function is automatically passed two arguments – the event object and a ui object containing the suggestion that was selected. We use this function to format the recipient name and add it to the <div>. We simply create a <span> element to hold the text and an anchor element that can be used to remove the recipient. Once the formatted recipient has been created we just insert it directly before the camouflaged <input>.

Lastly we add a handler for the change event; this function will be invoked whenever the value of the <input> that the Autocomplete is associated with changes. We just use it to remove the value from the <input> because we’ve already added the formatted version to our container <div>. The carat looks a little high up once a formatted contact name has been added to the <div> so we also use this event handler to correct this.

This is all the configuration we need for this particular implementation, but there are still a couple of additional functions we need to add to tidy things up a little. After the autocomplete() method add the following code:

//add click handler to friends div
$("#friends").click(function(){

	//focus 'to' field
	$("#to").focus();
});

//add live handler for clicks on remove links
$(".remove", document.getElementById("friends")).live("click", function(){

	//remove current friend
	$(this).parent().remove();

	//correct 'to' field position
	if($("#friends span").length === 0) {
		$("#to").css("top", 0);
	}
});

The <input> that our Autocomplete is attached to is partially hidden and its container <div> is styled so that it appears like the other fields on the form; to complete the deception, we add a click handler to the container <div> so that clicking anywhere within it focuses the actual <input>. Visually and functionally now the <div> should be indistinguishable from a regular field.

We also need to handle clicks on the anchor that is added to each formatted recipient; we use jQuery’s live() method because these elements may or may not exist on the page at any given time and it is easier than binding the handler function each time we create one of these anchors. Whenever one of these anchors is clicked all we do is navigate up to the parent of the anchor that was clicked and then remove it from the page. Remember when we corrected the position of the carat earlier in the script? We just need to check whether all the recipients have been removed and if so, reset its position back to its default.


Step 5 Additional Code and Resources

I used a MySql database containing a table listing each of the recipient names, and the following PHP file to accept the data sent by the getJSON() method and pull matching recipients from the database:

<?php

	//connection information
	$host = "localhost";
	$user = "root";
	$password = "your_mysql_password_here";
	$database = "test";
	$param = $_GET["term"];

	//make connection
	$server = mysql_connect($host, $user, $password);
	$connection = mysql_select_db($database, $server);

	//query the database
	$query = mysql_query("SELECT * FROM friends WHERE name REGEXP '^$param'");

	//build array of results
	for ($x = 0, $numrows = mysql_num_rows($query); $x  $row["name"]);
	}

	//echo JSON to page
	$response = $_GET["callback"] . "(" . json_encode($friends) . ")";
	echo $response;

	mysql_close($server);

?>

To run the downloadable example files, you’ll need a development web server with PHP installed and configured, as well as MySql and the appropriate database and table. When a letter is typed into the ‘to’ field, this letter is passed to the server and used to pull out each name that begins with the letter that was typed. The matching names are then passed back to the page as JSON and displayed in the suggestion menu:

This tutorial showed how to replicate Facebook’s message sending form, specifically, the way friends are added to the messaging form as recipients using an Autocomplete, and how the friend names are formatted once they have been added so that they can easily be removed. Our example form doesn’t actually do anything, but what we would need to do to actually send the form would be to pass the contents of the form to a server-side file for sending using AJAX, which could easily be hooked into the submit event of the send button used on the form.

The recipients would need to have some kind of meaning to back-end system of course, and would probably be mapped to email addresses in the database. We’d need to retrieve the textual content of each of the <span> elements before passing back to the server, although this would be a fairly trivial matter.

The jQuery UI Autocomplete widget makes it easy to connect to any datasource and contains a rich suite of event handlers that we can supply functions to in order to react to text being entered into the associated field, or a suggestion being selected from the menu. The widget is styled using jQuery UI’s extensive CSS framework and can easily be changed so that it matches your existing site theme. All in all, it’s an excellent widget that is easy to use and provides great functionality.



Automatically replace content in PRE tags by HTML Entities

Automatically replace content in PRE tags by HTML Entities

Just paste the following in your functions.php file. Once saved, all your content with <pre> and </pre> tags will be automatically replaced by html entities.

function pre_entities($matches) {
	return str_replace($matches[1],htmlentities($matches[1]),$matches[0]);
}
//to html entities;  assume content is in the "content" variable
$content = preg_replace_callback('/<pre.*?>(.*?)<\/pre>/imsu',pre_entities, $content);

Credits goes to David Walsh for this very cool tip!

By the way, I recently reviewed the new “WpSEO” plugin on CatsWhoBlog so you should definitely take a look!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

Automatically replace content in PRE tags by HTML Entities

Quick Tip: How to Target IE6, IE7, and IE8 Uniquely with 4 Characters

Quick Tip: How to Target IE6, IE7, and IE8 Uniquely with 4 Characters

Two months ago, I, in a video quick tip, demonstrated how to use the underscore and star hacks to target Internet Explorer 6 and 7 in your stylesheets. In today’s quick tip, we’ll take things one step further, as we introduce a new hack that targets IE8 and below as well. It should be noted that this is not a best practice, and conditional comments should be used instead 98% of the time. With that said, it’s always important to know what you can do – plus it’s fun, right?


IE8 and Below

The key to targeting Internet Explorer 8 and below, with a hack, is to append “\9″ to the end of your style. For example:

body {
 color: red; /* all browsers, of course */
 color : green\9; /* IE8 and below */
}

It’s important to note that it must be “\9″. Unfortunately you can’t replace this with something along the lines of “\IE”, like I attempted to do so. Even “\8″ won’t work; it must be “\9″.


IE7 and Below

As we learned in the quick tip from January, we can use the * symbol to target IE7 and below, like so:

body {
 color: red; /* all browsers, of course */
 color : green\9; /* IE8 and below */
 *color : yellow; /* IE7 and below */
}

IE6

Lastly, we have the underscore hack, which most designers are familiar with by now. Rather than the * symbol, we use the underscore. This will target only Internet Explorer 6.

body {
 color: red; /* all browsers, of course */
 color : green\9; /* IE8 and below */
 *color : yellow; /* IE7 and below */
 _color : orange; /* IE6 */
}

A Note About CSS Hacks

It’s worth noting that I’m not advocating the use of hacks in your stylesheets in any way. On the contrary, you should almost always use conditional comments. However, that doesn’t mean that it isn’t helpful to know what you can technically get away with, whether it be for debugging, or showing off to your friends!

The biggest concern is that hacks aren’t future proof, at least not really. For example, what if, with the release of Firefox 4, they, too, recognized properties prepended with the * hack. They probably never would for compatibility reasons, however, if they did, that could potentially ruin a portion of your layout. Ultimately, just be wise when using hacks. If you only need to change one or two properties to make IE6 happy, then I don’t see any harm in using the underscore hack directly in your stylesheet. The world won’t end. However, if there are a handful of changes, be sure to use conditional comments!

<!--[if lte IE 7]>
Make IE7 happy.
<![endif]-->

Thanks for reading and watching!



Best WordPress Plugins By Category

Premium WordPress Plugins by category

– Advertising –

  • OIO Publisher – Complete plugin that removes all hassle for bloggers who manage advertising. Automates banners, text links, paid reviews, and collects the money for you. [Full Review]

– Affiliates –

  • Auction Thumbs – Plugin that allows you to easily integrate eBay Partner Network ads into your WordPress Blog. [Full Review]
  • PHP Bay Pro – Premium plugin that integrates eBay auction ads into your WordPress blog. [Full Review]
  • WP Affiliate Pro – Allows you to manage your affiliate links from within your WordPress dashboard. Also allows you to mask links and a number of other features. [Full Review]
  • WP Ninja Affiliate – Similar to WP Affiliate Pro plugin, but provides some additional features including multiple keywords and caching. [Full Review]

– SEO –

  • WP SEO Sniper – Extreme SEO plugin designed to give people conscious of SEO full control over their blogs from the WordPress dashboard. Significant upgrade to the All-in-One SEO Pack plugin. [Full Review]

– Websites –

  • WP Review Site – Simply activate theme and plugin to create a full-featured review website. No additional work needed, allowing you to make a number of these sites quickly! [Full Review]

Free WordPress Plugins

– Admin Tools –

  • Gamer’s Pack – Makes your blog viewable using the Nintendo DS, Nintendo Wii, and PSP gaming systems. [Full Review]
  • GoCodes – Easily create redirects from your WordPress Dashboard that point anywhere. Great for hiding affiliate links. [Full Review]
  • Google Sitemap – Creates a fully-compliant sitemap for search engines. [Full Review]
  • Greet Box – Identifies where traffic is being referred from and displays the appropriate welcome message to them, encouraging to subscribe to your feed, Digg or Stumble your posts, etc. [Full Review]
  • In Series – Allows you to easily group a series of posts into a series. [Full Review]
  • MobilePress – Optimizes your WordPress blog for mobile phones including the popular iPhone. [Full Review]
  • No Self Ping – Prevents your blog from sending pingbacks internally to your other posts. [Full Review]
  • WP-o-Matic – Allows users to collect feeds and auto-generate posts on your blog. [Full Review]
  • WordPress Backup – Plugin that backups up your WordPress themes, WordPress plugins, images, and other non-database stuff. Works with WP-DB Manager. [Full Review]
  • WP-DB Manager – Plugin that gives you full control over your WordPress database backups. Works with the WordPress Backup plugin. [Full Review]
  • WP Sticky – Allows users to feature a post at the top of their homepage for a day or permanently. [Full Review]
  • WP-Super Cache – Creates a cache of your posts to avoid server load. Great for surviving a Digg. [Full Review]

– Advertising –

– Authors –

– Comments –

  • CubePoints – CubePoints allows you to choose a certain amount of points for each comment posted by a certain commentator. You can offer premium content, allow readers to purchase merchandise or maybe even an advertisement for your blog with a certain amount of points. [Full Review]
  • Keyword Luv – Adds an extra field to your comments where people can enter their website so they don’t add their website’s name in the name field for SEO anchor text purposes. [Full Review]
  • Liz Comment Count – Displays a comment count in a similar fashion to the Feedburner feed count widget. [Full Review]
  • MyAvatars – Automatically inserts the commentators MyBlogLog avatar next to their comment using the e-mail address provided. If unavailable, it will attempt to pull the bloggers Gravatar. [Full Review]
  • Show Top Commentators – Allows you to display your top commentators automatically in a place of your choosing. Great for encouraging comments. [Full Review]
  • Smilies Themer – Plugin that offers a variety of smilies styles to place in the comments section of your blog. [Full Review]
  • Subscribe to Comments – Allows readers to receive e-mail notifications when a follow up comment is left. [Full Review]

– Domaining –

  • Domain Name Portfolio – This plugin automatically creates a page in WordPress that domainers can use to display their domain portfolio. Everything is controlled from the dashboard. [Full Review]

– Downloads –

– Feeds –

– Forums –

  • RS Discuss – Plugin that allows you to easily integrate a forum into your existing WordPress blog. [Full Review]

– Maintenance –

– Miscellaneous –

  • Best Posts Summary – Automatically generates a daily, weekly, or monthly review post. Includes both post titles and brief descriptions. [Full Review]
  • BreadCrumb Navigation XT – Allows you to provide your readers with additional blog navigation. [Full Review]
  • Get Firefox Banner – Shows a banner to IE6 and IE7 web browser users recommending they switch to Firefox. Great for blogs whose WordPress theme is optimized for Firefox. [Full Review]
  • Popularity Contest – Monitors your website traffic and gives you reports on your popular posts. Plugin is fully customizable allowing you to set the values used to calculate your posts popularity. [Full Review]
  • WP-eCommerce – Plugin that allows you to create an online shop on your WordPress blog [Full Review]
  • WP-Email – Allows you to add an “Email This!” button to your WordPress blog. [Full Review]
  • WP-Submission – Creates a submission page then places all submissions into a post draft. Ideal for group writing projects. [Full Review]

– Related Posts –

– SEO –

  • All-in-One SEO Pack – The Ultimate SEO WordPress plugin. Allows you to set your homepage meta information and automatically generate custom meta information for your individual posts. [Full Review]
  • Permalink Redirect – Creates a 301 Redirect to avoid duplicate content penalties with search engines. Also includes a Feedburner redirect. [Full Review]

– Tags –

– Video –

  • All-in-One Video Pack – All-in-One Video Pack includes every functionality you might need for video and rich-media, including the ability to upload/ record/import videos directly to your post, edit and remix content with an online video editor, enable video responses, manage and track your video content, create playlists, etc. [Full Review]

20 Helpful jQuery Methods you Should be Using

20 Helpful jQuery Methods you Should be Using

So you’ve been playing with jQuery for a while now, you’re starting to get the hang of it, and you’re really liking it! Are you ready to take your jQuery knowledge to level two? Today, I’ll demonstrate twenty functions and features you probably haven’t seen before!


1 after() / before()

Sometimes you want to insert something into the DOM, but you don’t have any good hooks to do it with; append() or prepend() aren’t going to cut it and you don’t want to add an extra element or id. These two functions might be what you need. They allow you to insert elements into the DOM just before or after another element, so the new element is a sibling of the older one.

$('#child').after($('<p />')).text('This becomes a sibling of #child'));
$('#child').before($('<p />')).text('Same here, but this is go about #child'));

You can also do this if you’re working primarily with the element you want to insert; just use the insertAfter() or insertBefore functions.

$('<p>I\'ll be a sibling of #child</p>').insertAfter($('#child'));

2 change()

The change() method is an event handler, just like click() or hover(). The change event is for textareas, text inputs, and select boxes, and it will fire when the value of the target element is changed; note that this is different from the focusOut() or blur() event handlers, which fire when the element loses focus, whether its value has changed or not.

The change() event is perfect for client-side validation; it’s much better than blur(), because you won’t be re-validating fields if the user doesn’t change the value.

$('input[type=text]').change(function () {
    switch (this.id) {
        /* some validation code here */
    }
});??????????

3 Context

Context is both a parameter and a property in jQuery. When collecting elements, you can pass in a second parameter to the jQuery function. This parameter, the context, will usually be a DOM element, and it limits the elements returned to item matching your selector that are children of the context element. That might sound a bit confusing, so check out this example:

<p class="hello">Hello World</p>
<div id="wrap">
    <p class="hello">Hello World</p>
</div>
var hi1 = $('.hello'),
    hi2 = $('.hello', $('#wrap').get(0));

console.group('hi1');
console.log("Number of elements in collection:", hi1.length);
console.log("Context of the collection:", hi1.context);
console.groupEnd();
console.group('hi2');
console.log("Number of elements in collection:", hi2.length);
console.log("Context of the collection:", hi2.context);
console.groupEnd();
context example

So where would this be useful? One place might be inside an event handler function. If you’d like to get an element within the one the event was fired on, you could pass this as the context:

$('ul#options li').click(function () {
    $('a', this) . . .
});

4 data() / removeData()

Have you ever wanted to store some bit of information about an element? You can do that easily with the data() method. To set a value, you can pass in two parameters (a key and a value) or just one (an object).

$('#wrap').data('myKey', 'myValue');
$('#container').data({ myOtherKey : 'myOtherValue', year : 2010 });

To get your data back, just call the method with the key of value you want.

$('#container').data('myOtherKey'); //returns 'myOtherValue'
$('#container').data('year'); //returns 2010

To get all the data that corresponds with an element, call data without any parameters; you’ll get an object with all the keys and values you’ve given to that item.
If you want to delete a key/value pair after you’ve added it to an element, just call removeData(), passing in the correct key.

$('#container').removeData('myOtherKey');

5 queue() / dequeue()

The queue() and dequeue() functions deal with animations. A queue is list of animations to be executed on an element; be default, an element’s queue is named ‘fx.’ Let’s set up a scenario:

HTML

<ul>
  <li id="start">Start Animating</li>
  <li id="reset">Stop Animating</li>
  <li id="add">Add to Queue</li>
</ul>
<div style="width:150px; height:150px; background:#ececec;"></div>

JavaScript

$('#start').click(animateBox);

$('#reset').click(function() {
    $('div').queue('fx', []);
});

$('#add').click(function() {
    $('div').queue( function(){
        $(this).animate({ height : '-=25'}, 2000);
        $(this).dequeue();
    });
});

function animateBox() {
  $('div').slideUp(2000)
           .slideDown(2000)
           .hide(2000)
           .show(2000, animateBox);
}

So, here’s what’s going on: in the animateBox function, we’re setting up a queue of animations; notice that the last one calls back to the function, so this will continually repeat the queue. When we click li#start, the function is called and the queue begins. When we click li#reset, the current animation finishes, and then the div stops animating. What we’ve done with jQuery is set the queue named ‘fx’ (remember, the default queue) to an empty array; essentially, we’ve emptied the queue. And what about when we click li#add? First, we’re calling the queue function on the div; this adds the function we pass into it to the end of the queue; since we didn’t specify a queue as the first parameter, ‘fx’ is used. In that function, we animate the div, and then call dequeue() on the div, which removes this function from the queue and continues the queue; the queue will continue repeating, but this function will not be part of it.


6 delay()

When you’re queuing up a chain of animations, you can use the delay() method to pause the animation for a length of time; pass that time as a parameter in milliseconds.

$('div').hide().delay(2000).show(); // div will stay hidden for 2 seconds before showing.

7 bind(), unbind(), live(), and die()

Did you know that when you add a click event to an element like this . . .

$('#el').click(function () { /*******/ });

. . . you’re really just using a wrapper for the bind() method? To use the bind() method itself, you can pass the event type as the first parameter and then the function as the second.

If you use a lot of events, you can categorize them with namespacing; just add a period after the event name and add your namespace.

$('#el').bind('click', function () { /*******/ });
$('#el').bind('click.toolbarEvents', function () { /*******/ }); // namespaced

You can also assign the same function to multiple events at the same time, by separating them with spaces. So if you wanted to make a hover effect, you could start this way:

$('#el').bind('mouseover mouseout', function () { /*******/ });

You can also pass data to the function if you’d like, by adding a third parameter (in the second position).

$('#el').bind('click', { status : 'user-ready' }, function () {
    switch(event.data.status) {
    /********/
    }
});

Sooner or later, you’ll find yourself inserting element into the DOM via an event handler; however, you’ll find that the event handlers you’ve made with bind (or its wrappers) don’t work for inserted elements. In cases like this, you’ll need to use the live() (or delegate) method; this will add the event handlers to the appropriate inserted elements.

$('.toggle').live(function () {
    /* code */
    $('<span class="toggle">Enable Beta Features</span>').appendTo($('#optionsPanel'));
    /* more code */
});

To remove event handlers created with bind(), use the unbind() method. If you don’t pass it any parameters, it will remove all the handlers; you can pass in the event type to only remove event handlers of that type; to remove events from a specific namespace, add the namespace, or use it alone. If you just want to remove a certain function, pass its name along as the second parameter.

$('button').unbind(); // removes all
$('button').unbind('click'); // removes all clicks
$('button').unbind('.toolbarEvents'); // removes all events from the toolbarEvents namespace
$('button').unbind('click.toolbarEvents'); // removes all clicks from the toolbarEvents namespace
$('button').unbind('click', myFunction); // removes that one handler

Note that you can bind/unbind functions you’ve passed in anonymously; this only works with the functions name.
If you’re trying to unbind an event from inside the function called by the event, just pass unbind() the event object.

$('p').bind('click', function (event) {
    $('p').unbind(event);
} );

You can’t use unbind() for live events; instead, use the die(). Without parameters, it will remove all live events from the element collection; you can also pass it just the event type, of the event type and the function.

$('span').die(); // removes all
$('span').die('mouseover'); // removes all mouseovers
$('span').die('mouseover', fn); // remove that one handler

And now, you can wield jQuery events with deftness and power!

You should also review the delegate() method, as there can be substantial performance benefits to using it over live().


8 eq()

If you’re looking for a specific element within a set of elements, you can pass the index of the element to the eq() method and get a single jQuery element. Pass in a negative index to count back from the end of the set.

var ps = $('p');
console.log(ps.length); // logs 3;
ps.eq(1).addClass('emphasis'); // just adds the class to the second item (index in zero-based)

You can also use :eq() in your selectors; so the previous example could have been done like this:

$('p:eq(1)').addClass('emphasis');

9 get()

When getting a collection of element, jQuery returns them as a jQuery object, so you have access to all the methods. If you just want the raw DOM elements, you can use the get() method.

You can specify an index to get only one element.

alert( $('p') ); // [object Object] - the jquery object
alert( $('p').get(1) ); // [object HTMLParagraphElement]

10 grep()

If you’re not familiar with Unix/Linix shells, you might not have heard the term grep. In a terminal, it’s a text search utility; but here in jQuery, we use it to filter an array of elements. It’s not a method of a jQuery collection; you pass in the array as the first parameter and the filtering function as the second parameter. That filter function takes two parameters itself: an element from the array and its index. That filter function should perform its work and return a true or false value. Be default, all the items that return true will be kept. You can add a third parameter, a boolean, to invert the results and kept the items that return false.

Jeffrey Way did a great quick tip about the $.grep not long ago; check that out to see how to use it!

var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');

nums = $.grep(nums, function(num, index) {
  // num = the current value for the item in the array
  // index = the index of the item in the array
  return num > 5; // returns a boolean
});

console.log(nums) // 6,7,8,9,10

11 Pseudo-Selectors

Sizzle, the CSS Selector engine inside jQuery, offers quite a few pseudo-selectors to make the job of selecting the elements you want easy. Check out these interesting ones:

$(':animated'); // returns all elements currently animating
$(':contains(me)'); // returns all elements with the text 'me'
$(':empty'); // returns all elements with no child nodes or text
$(':parent'); // returns all elements with child nodes or text
$('li:even'); // returns all even-index elements (in this case, <li>s)
$('li:odd'); // can you guess?
$(':header'); // returns all h1 - h6s.
$('li:gt(4)'); // returns all elements with an (zero-based) index greater than the given number
$('li:lt(4)'); // returns all element with an index less than the given number
$(':only-child'); // returns all . . . well, it should be obvious

There are more, of course, but these are the unique ones.


12 isArray() / isEmptyObject() / isFunction() / isPlainObject()

Sometimes you want to make sure the parameter that was passed to a function was the corrent type; these functions make it easy to do. The first three are pretty self explanatory:

$.isArray([1, 2, 3]); // returns true
$.isEmptyObject({}); // returns true
$.isFunction(function () { /****/ }); // returns true

The next one isn’t as obvious; isPlainObject() will return true if the parameter passed in was created as an object literal, or with new Object().

function Person(name) {
	this.name = name
	return this;
}
$.isPlainObject({})); // returns true
$.isPlainObject(new Object()); // returns true
$.isPlainObject(new Person()); // returns false

13 makeArray()

When you create a collection of DOM elements with jQuery, you’re returned a jQuery object; in some situations, you might prefer that this be an array or regular DOM elements; the makeArray() function can do just that.

var ps = $('p');
$.isArray(ps); //returns false;
ps = $.makeArray(ps);
$.isArray(ps); // returns true;

14 map()

The map() method is remotely similar to grep(). As you might expect, it takes one parameter, a function. That function can have two parameters: the index of the current element and the element itself. Here’s what happens: the function that you pass in will be run once for each item in the collection; whatever value is returned from that function takes the place of the item it was run for in the collection.

$('ul#nav li a').map(function() {
  return $(this).attr('title');
});  // now the collection is the link titles
// this could be the beginning of a tooltip plugin.

15 parseJSON()

If you’re using $.post or $.get—and in other situations that you work with JSON strings—you’ll find the parseJSON function useful. It’s nice that this function uses the browsers built-in JSON parser if it has one (which will obviously be faster).

$.post('somePage.php', function (data) {
    /*****/
data =  $.parseJSON(data);
    /*****/
});

16 proxy()

If you have a function as a property of an object, and that function uses other properties of the object, you can’t call that function from within other functions and get the right results. I know that was confusing, so let’s look at a quick example:

var person = {
  name : "Andrew",
  meet : function () {
    alert('Hi! My name is ' + this.name);
  }
};
person.meet();
$('#test').click(person.meet);

By itself, person.meet() will alert correctly; but when it’s called by the event handler, it will alert “Hi! My name is undefined.” This is because the function is not being called in the right context. To fix this, we can use the proxy() function:

$('#test').click($.proxy(person.meet, person));
// we could also do $.proxy(person, "meet")

The first parameter of the proxy function is the method to run; the second is the context we should run it in. Alternatively, we can pass the context first, and the method name as a string second. Now you’ll find that the function alerts correctly.

Prefer a video quick tip on $.proxy?


17 replaceAll() / replaceWith()

If you’d like to replace DOM elements with other ones, here’s how to do it. We can call replaceAll() on elements we’ve collected or created, passing in a selector for the elements we’d like to replace. In this example, all elements with the error class will be replaced with the span we’ve created.

$('<span class="fixed">The error has been corrected</span>').replaceAll('.error');

The replaceWith() method just reverses the selectors; find the ones you want to replace first:

$('.error').replaceWith('<span class="fixed">The error has been corrected</span>');

You can also pass these two methods functions that will return elements or HTML strings.


18 serialize() / serializeArray()

The serialize() method is what to use for encoding the values in a form into a string.

HTML

<form>
    <input type="text" name="name" value="John Doe" />
    <input type="text" name="url" value="http://www.example.com" />
</form>

JavaScript

console.log($('form').serialize());??? // logs : name=John+Doe&url=http%3A%2F%2Fwww.example.com

You can use serializeArray() to turn the form values into an array of objects instead of a string:

console.log($('form').serializeArray());???
// logs : [{ name : 'name', value : 'John Doe'} , { name : 'url', value : 'http://www.example.com' } ]

19 siblings()

You can probably guess what the siblings() method does; it will return a collection of the siblings of the whatever items are in your original collections:

<div> . . . </div>
<p> . . . </p>
<span> . . . </span>
$('p').siblings(); // returns <div>, <span>

20 wrap() / wrapAll() / wrapInner()

These three functions make it easy to wrap elements in other elements. First off, I’ll mention that all three take one parameter: either an element (which is an HTML string, a CSS selctor, a jQuery object, or a DOM element) or a function that returns an element.
The wrap() method wraps each item in the collection with the assigned element:

$('p').wrap('<div class="warning" />'); // all paragraphs are now wrapped in a div.warning

The wrapAll() will wrap one element around all the elements in the collection; this means that the elements in the collection will be moved to a new spot in the DOM; they’ll line up at the place of the first element in the collection and be wrapped there:

HTML, Before:

<p>
    <span> . . . </span>
    <span class="moveMe"> . . . </span>
    <span class="moveMe"> . . . </span>
</p>
<p>
    <span> . . . </span>
    <span class="moveMe"> . . . </span>
    <span class="moveMe"> . . . </span>
</p>

JavaScript

$('.moveMe').wrapAll(document.createElement('div'));

HTML, After:

<p>
    <span> . . . </span>
    <div>
        <span class="moveMe"> . . . </span>
        <span class="moveMe"> . . . </span>
        <span class="moveMe"> . . . </span>
        <span class="moveMe"> . . . </span>
    </div>
</p>
<p>
    <span> . . . </span>
</p>

Finally, the wrapInner function wraps everything inside each element in the collecting with the given element:

HTML, Before:

<p>
    <span> . . . </span>
    <span> . . . </span>
</p>

JavaScript:

$('p').wrapInner($('<div />'));

HTML, After:

<p>
    <div>
        <span> . . . </span>
        <span> . . . </span>
    </div>
</p>

Conclusion

Well, now you’ve got more than twenty new jQuery features to play with on your next project; have fun with them!

CodeIgniter from Scratch: Shopping Cart

CodeIgniter from Scratch: Shopping Cart

Today, we are going to take a look at the Shopping Cart library for CodeIgniter. This useful class allows us to add and remove items to a shopping cart, update them, and calculate prices. I will demonstrate how you can build a simple shopping cart system with the help of this library..


Catch Up


Day 12: Shopping Cart

Final Project



Build an Awesome Status Board: New Premium Tutorial

Build an Awesome Status Board: New Premium Tutorial

When Panic unveiled their status panel to the world, I was both impressed and inspired. In today’s in depth Premium tutorial and screencast, I’ll show you how to built a similar status board! Help give back to Nettuts+ by joining our Premium program.

Join Net Premium

NETTUTS+ Screencasts and Bonus Tutorials

For those unfamiliar, the family of TUTS sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!