Skip to navigation | Skip to content

Share your knowledge. Make a difference.

Web Development Tips & Tricks

1 - I can do better 2 - Jury's out 3 - Pretty darn good 4 - Splendiferous 5 - Awesometastic (by 5 people)   Your rating: 1 - I can do better 2 - Jury's out 3 - Pretty darn good 4 - Splendiferous 5 - Awesometastic

Ranked #716 in Tech, #18167 overall

Rated G. (Control what you see)

About this Lens

 

This lens is a place for me to present my tips, tricks, tutorials, views, etc. on much of the latest topics in web design and development. I'll be focusing on web standards, usability, best practices and coding tutorials; specifically in JavaScript, Ajax, PHP and CSS.

Accessing the Digg API with PHP 

Early in 2007, Digg.com introduced its API which allows developers to access all of Digg's data back to 2004. Requests are sent to the Digg servers with a simple call to http://services.digg.com and responses are sent back in an XML, JSON, JavaScript or PHP type. For this tutorial, we're going to focus on PHP responses.

I'm going to ignore the Services_Digg Pear package for now, since it has not yet been accepted as an official Pear package. That said, the best way to access the API in PHP is through the cURL library and since I've always been a fan of the wheel and I see no reason to reinvent it, I'm going to use JasLab's PHP Digg toolkit. The toolkit is class that you'll need to unzip and upload to your server. Then simply add it as an include in the PHP file you'll be working in and your ready to go. The toolkit will handle connecting to the Digg server with curl_setopt, building the request and parsing the response. It will return a nice, clean array of arrays containing all of the diggs and/or comments you've requested. Let's get started.

The first thing we're going to do is create a new instance of diggclass; the main class in the digg toolkit. Then, to get all diggs from a single user, just call the getUserDiggs function on your class instance and store the result in a new array. getUserDiggs takes several optional parameters, but the main values that you'll want to pass are $user, $count and $offset; where $count is the number of diggs to return and $offset is the starting point for which to get diggs (0 means start with the most recent digg). You can also pass start and ending time values; check out the toolkit documentation for more information.

View the code and a live demo at Spegele.com »

W3c Releases HTML 5 Public Working Draft 

Yesterday, the W3C published two documents that are very important to the future of web development. They released technical reports on HTML 5 and HTML 5 differences from HTML 4. This draft represents a major leap forward for HTML which has not seen an update since HTML 4 was adopted in December of 1999.

The new elements and attributes that have been added into version 5 focus entirely on semantics and structure. In fact, the <font> element as well as all presentational attributes, such as align, width, height, background and style, have been removed in HTML 5. It is clear that by the time this draft is accepted as a standard, CSS will not only be the norm, but will be required.

Besides removing presentational elements and attributes, HTML 5 is also focusing on structure with the additions of several key elements. Most notably, <section>, <article>, <aside>, <header>, <footer> and <nav>. These new elements will be used for easily defining your page structure, rather than having to use <div id="nav"> or <div id="header">. This standardizes what are already the most common designations for these sections of a web page, making both the HTML and CSS code easier to code and read. Other notable elements with a great deal of potential include <dialog> and its child elements <dt> and <dd>, which can be used to mark up a conversation, <figure>, which can associate a caption with some embedded content, <audio> and <video>, for multimedia content, <meter>, for representing measurements, and <datagrid>, which represents and interactive tree list or tabular data.

Form validation will get much easier, as well, with the introduction of 10 new input types; datetime, datetime-local, date, month, week, time, number, range, email and url. These new types mean that the text input type will no longer be a catch-all for any kind of input and browsers will now be able to do the field limiting and validation for you.

There are some notable new attributes as well. The ping attribute in <a> and <area> elements allow for a list of URIs to be pinged when a link is followed. <a> and <area> will also now have the media attribute. value is no longer deprecated for <li> and autofocus can now be specified on an <input> element.

The HTML version 5 specification is exciting news for web developers everywhere as the markup language is set to take its first steps in nearly a decade. Which attributes and elements are you most excited to see? What new tricks do you think you'll be able to pull of with them?

Jump into the HTML 5 discussion at Spegele.com »

PHP Classes Part 3: Static Keywords, Constants and the Scope Resolution Operator 

From time to time in your PHP class adventures you may need to declare a variable as static or define a constant value. If you've ever used these objects in a language similar in syntax (i.e. C++), this should all be familiar, but if not, this tutorial will give you all the information to begin employing these important concepts. Those of you who are true PHP newbs, might want to check out the first 2 parts of this series; The Basics of PHP Classes and The Basics of PHP Abstract Classes.

Let's start by defining static varibles and constants. A constant is a value that you define in your class which must be equal to a constant expression. This means that you constant can be set to any string or number, but not to the value of a variable, the result of a function call or the result of a mathematical expression. The constant will be inherited by any and all instances of that class which you create. The static keyword, on the other hand, can be applied to any member or method of a class. These members and methods are no different than any other, except that they can be accessed without creating an instance of that class.

Defining a constant is simple. You precede the name of your constant with the const keyword and set it equal to whatever your constant value is. To access the value of your constant, you'll need to use the scope resolution operator (::) preceded by either self (from within the class) or the name of the class (from outside of the class).

View the code at Spegele.com »

An Introduction to Working with PHP and MySQL 

For those of you out there who are still new to PHP, I'd like to discuss one of the languages most useful and most powerful features; its integration with MySQL. PHP and MySQL are integrated so seamlessly that almost anyone can create a dynamic web application based on the pair.

Let's jump right into it. For this tutorial, I'm going to assume that your server is already set up with PHP4+ and MySQL 4.1+. LAMPHowTo.com has a great tutorial to help you set your server up if you've decided to host your own site. OK, so now that you're all set up, the first thing you'll need to do in your PHP code is connect to the database. For this step you'll need to know the path to your database server, your database username and your password. Plug that information into following code and you'll be ready to start working with your new database.

View the code at Spegele.com »

The Basics of PHP Abstract Classes 

Today I'm going to delve a bit deeper into PHP classes and talk about abstract classes. An abstract class is a core class which provides default behavior for and is extended by sub classes. It is important to note that an abstract class is very different from an interface. An interface defines how you work with a class, but does not define how the class itself works. With an abstract class you define the default behaviors of the class as well as what other functions the class needs to perform. Those other functions are simply declared in the abstract class, but are then defined in a class extension.

Let's take a look at a very simple example where we have an abstract class called shape which defines two variables, base and height, a function to get and store those values and the declaration of a draw function.

View the code at Spegele.com »

Enlarge Thumbnails When Hovered Over Using Only CSS 

Here's a nice bit of CSS that will enlarge an image when that it is hovered over. What you need to do is create a link that contains two separate image tags and enclose that within a div that you can specify the height and width of. You can either a small image and a large image, or simply use a single large image and specify a smaller size in one of the image tags. The image tag that you specify class="full" on is your large image that will display when the thumbnail is hovered over. Here's what the HTML to achieve this should look like:

View the code and a live demo at Spegele.com »

Using JavaScript to Limit the Input Allowed in a TextArea 

Here's a simple yet very useful little JavaScript function I wrote recently which limits the number of characters a user can put into a standard <textarea> while displaying a running count of the number of characters left. The function takes 3 inputs; the ID of an element which contains the current count (in this case, a <span>), the ID of the input element, and the desired character limit. The function is called on the key up of every keystroke for that input. It then counts the length of the input, checks if more characters are allowed and pushes the number of characters remaining out the the count element. The function will trim the last character off of the input string if no more characters are allowed.

The first thing you'll need to do is create the element to hold the count and the input element. The input element will utilize onkeyup to call charactersLeft().

View the code and a live demo at Spegele.com »

Preferred Web Scripting Languages 

Loading poll. Please Wait...

Fading an Element In and Out with JavaScript 

Today I've got a quick and easy way to fade any element in and out using JavaScript. This is great way to add a little something extra to your site, especially if it is combined with a slide or some other method of hiding an element. It is important to note that is fade script does not truly "hide" an element from the page, rather it simply makes the element invisible to the user.

Let's jump right in. The first thing we need to do is write our changeOpacity() function. This function is what will actually change the opacity of the element. This will not achieve the fade, however, because it will only change the opacity of the element from one value to another. It could also be used for any one off opacity changes you need to make. The function takes just 2 variables as input; el and opacity. el is the name of the element you want to change the opacity of and opacity the the new opacity that you want.

View the code and a live demo at Spegele.com »

Using CSS Sprites to Optimize Your Image Loading 

The term Sprite originates from the early computer graphics technique of using many small images to build a single larger image. This technique became unnecessary as computers grew ever more powerful, though, so the term came to refer to just the single larger image. The term was a natural fit when web designers began combining their icons, thumbnails and other images into a single larger image. And hey, it rolls off the tongue a lot easier than Single Image Multi Replacement. So why are designers combining all of their smaller images into one larger image? To save on bandwith, loading times and server requests. In the early days of the web design, splicing your images gave the appearance of faster load times since individual splices load separately. In reality, a spliced image takes longer to load. The sum is actually less than the whole of its parts. A single sprite will be significantly smaller (in file size) than the sum of all of the individual images that it's made up of.

So now that we know what sprites are and why we should use them, let's figure out how to use them. The first step is to create the sprite. This is pretty straight forward; just open up your favorite image editor and combine all of your icons or thumbnails into one graphic. You can line them up however you like, just keep in mind that the more organized they are, the easier your job will be. Putting them all one on top of another or all side by side is the easiest way to do this. In my example, I've created two rows of icons; the standard icons on top and the hovered icons on the bottom.

The next step is to style the unordered list (<ul>) which will contain the icons. You don't have to put them in a list container, though. You could just keep them each in a separate span, paragraph, div, etc. But be careful if you don't use a list. You'll have to make some major edits to how and where the background image is defined. Here's how I styled my list:

View the code and a live demo at Spegele.com »

The Basics of PHP Classes 

OK, so everyone knows PHP lately. It's the simplest scripting language to learn and yet still an extremely powerful one. PHP is the language that many web developers start off with because of that simplicity. Unfortunately, though, too many developers stop there. Delving just a little bit deeper into the language reveals a tremendous amount of new possiblities.

Today I'm going to take a quick look at the basics of PHP classes. A class is an object that is described by the variables and powered by the functions contianed within it. The main benefit of using classes is to have one piece of code that allows you to create any number of instances of that object.

Let's say you wanted to write a class in PHP to define a virtual car. This wouldn't be worth the effort if you only need a single car, but if you need 2 or more, a class is the best way to maintain your variables and be sure that all of your cars will work the same. Some variables you might want in this class would be $wheels[4], $doors[2], $steeringWheel, $gasPedal, $brakePedal and $gearState. Some of yourfunctions would be function openDoor(), function accelerate(), function brake(), and function turn(). Your functions would be passed variables describing the actions, such as sending brake() a variable like $force and sending turn() the variable $direction. Lets take a look at the code to create a basic class in PHP:

View the code and a live demo at Spegele.com »

Some of My Favorite Web Development Resources 

W3Schools

HTML XHTML CSS JavaScript XML XSL ASP SQL ADO VBSc more...2 points

Ajaxian

Cleaning up the web with Ajax1 point

Scarf*oo

Web standards, techniques, random geekery and more more...1 point

Digital Web Magazine

Articles, tutorials, features, reviews, classified more...0 points

DevX

DevX is the leading provider of technical informat more...0 points

PHP.net

All you could ever hope to know about PHP0 points

Vitamin

A resource for web developers, designers and entre more...0 points

Webmonkey

The Web Developer's Resource0 points

CSS Drive

CSS gallery, code samples, tutorials, and more.0 points

Western NY Web Development

The need for web development tools has led many di more...0 points

Sending Multiple XMLHTTP Requests with a Single Script 

Here's another little script I put together while working on my upcoming RSS reader / homepage aggregator application. Everyone knows how to do a basic Ajax style XMLHTTP request lately, but trying to send multiple requests at the same time can be tricky. The simple solution is to create a separate script for each request, but that technique is very inefficient and completely falls apart if you don't know exactly how many simultaneous requests you are going to be making. In my case, a user of my app will be able to add as many modules to their homepage as they want (well, there may be need to be a limit, but it will be fairly high).

The code below creates an array of XMLHTTP request objects to be executed concurrently. The obvious benefit to this technique over simply running your requests in succession is that one or two slow requests will not stop your visitors from using the application. Each module will load as the response comes back; allowing the slow loading modules to be skipped for the time being.

The code is ready to be dropped directly into your page except for the two areas in red where you'll have to add code to handle your request responses and errors. You'll most likely be using a DOM function (such as document.getElementById(myElement).innerHTML = responseText) to write the response to your page. Use the following function call to initiate a request; where "myAjaxScript.php" would be replaced with the path of the script or page you are making a request of: sendRequest("myAjaxScript.php");

View the code at Spegele.com »

Using PHP to Parse and Display an RSS Feed 

Just thought I'd share a little PHP script that I wrote recently which takes an RSS feed, parses it and echoes it out on a page. The code itself is very simple and based on PHP5's simplexml_load_file function. The first section of code takes a predefined RSS feed, $feed, and loads the feed's XML into the variable $xml via the simplexml_load_file function. I've also added an @ in front of the function to suppress the long list of warnings and errors produced by a feed that fails to load. I then check to see that something has, in fact, been loaded into $xml, then begin loading the feed data. Accessing an individual element within an XML document is just as easy as loading the document itself. To access an element in the document, you simply write out the path of the element with each level of the tree separated by "->". For example, $site = $xml->channel[0]->title[0]; will load the title of the news feed into the variable $site. Check out the code and live demo below. This example takes the BBC World News front page RSS and echoes the channel information and the first 20 feed items.

I'm currently working on a Netvibes-style application that is based off of the use of this function. Check back in a few weeks when I'll be sharing a much more in depth version of the RSS reader.

View the code and a live demo at Spegele.com »

Recommended Web Development Reading 

Programming PHP

Amazon Price: $26.39 (as of 07/25/2008)

JavaScript: The Definitive Guide

Amazon Price: $31.49 (as of 07/25/2008)

AJAX and PHP: Building Responsive Web Applications

Amazon Price: $31.00 (as of 07/25/2008)

CSS Mastery: Advanced Web Standards Solutions

Amazon Price: $23.09 (as of 07/25/2008)

Designing Web Usability (VOICES)

Amazon Price: $34.64 (as of 07/25/2008)

Pure CSS Drop-Down Menu 

I know there are plenty of these to go around lately, but I recently completed a pure CSS drop-down menu and I thought I'd share it with the world. JavaScript drop-down menus tend to give me more headaches than they're worth and I haven't been able to find a pure CSS menu that suits my needs (mainly cross-browser compatibility), so I set out to build my own; turns out it wasn't nearly the adventure I thought it was going to be.

By using the typical IE HTML hacks ("<!--[if IE 7]>" and "<!--[if lte IE 6]>"), I've been able to get drop-down to work well in IE6, IE7, Firefox, Opera, Safari, Mac Firefox and Netscape 8. I've tried to make the code as clear and self-explanatory as possible, but if you have any questions, feel free to ask them in the comments section.

View the code and a live demo at Spegele.com »

Effectively Using the JavaScript with() Statement 

There is a lot of debate over the use of the JavaScript with() statement, and whether or not it does more harm than good. In truth, with() is one of the most useful JavaScript statements available to you; but if you use it properly. Using the with() statement, you can reduce the number object references and make your code far more readable. The following is a basic example of the statement in action:

function x not using with():
function x(){
 var a = document.form1.element1.value;
 var b = document.form1.element2.value;
 var c = document.form1.element3.options[
 document.form1.element3.selectedIndex].text;
}

function x rewritten using with():
function x(){
 with(document.form1){
  var a = element1.value;
  var b = element2.value;
  with(element3) {
   var c = options[selectedIndex].text
  }
 }
}

Read more at Spegele.com »

Becoming a True CSS Expert 

Becoming a true CSS expert takes a lot more than simply memorizing syntax and knowing how to position a div in both IE and Firefox. Great CSS is clean, efficient, organized, maintainable and reusable. The folks over at Vitamin recently put out a great feature with tips on how to do just that. Their advice?

- Keep CSS out of the markup
- Semantics is not just a buzz word
- Take advantage of commenting
- Know when to use conditional comments or hacks
- Organize selectors and declarations
- Create a framework
- Balance readability and optimization
- Master your text editor
- Use version control
- Create and maintain a style guide

Check out the full feature at ThinkVitamin.com »

New Guestbook 

coreybrown

What a terrific lens, jspegele! Thanks for joining our group.

Posted January 04, 2008

X
jspegele

About jspegele

I'm a 23 year old, full time web developer at a large corporation, freelance developer on the side and sometimes a blogger.

jspegele's Pages

See all of jspegele's pages