HTML

CSS Button Sprite Example

What IS A CSS Button Sprite?

Let me start off by explaining what an image sprite is. A sprite is basically one larger image that is made up of many smaller images. The idea of sprites is that you only need to load one image and then apply it to a smaller div or A tag so only a portion of the large image shows. Then depending on the background position of the image, you will only see one of the smaller images. This tutorial will be useful if you want to create button sprites, menu sprites, sprite animations or any other type of sprites.
If you would like to see an example on using these sprites to create a sprite animation, check out the sprite animation tutorial.

CSS Button Sprite Example

Below is showing you a css button sprite. This article will show you how to create this button sprite.
 

Above is the finished example of what this tutorial will show you. Mouse over this sprite button image and see how it works and bear in mind that we are only using one image to create the rollover effect. The button is actually an A (anchor) tag that has a height 32px which is half of the image sprite height. This way, only the top half of the image shows which is the up state part of the image.

Why should you use css sprites?

Before images and css items can be displayed on your webpage, your browser must request the item such as javascript files, images, css files, etc. Each request takes time and your browser must wait for a response and then download the file for it to be displayed. So in short, the less items means less time to request and download items, meaning less time to load a page. So using sprites will increase the speed at which your website loads.

Button Sprite

Button Sprite

Above is the css button sprite image I made to create the above button sprite with it’s two states. Normal state when it is untouched and second state is the hover state for when we mouse over it. Notice that the one image contains both up and down states and then as we mouse over it, we use css to adjust the background position of the image sprite to make it appear that the button state is changing.

Now for the code to get this all working

CSS Code

<style>
/* css to style the button */
#rollover {
	background: #FFF url("images/sprite.png");
	width: 180px;
	height: 32px;
	display: block; /* can use inline-block instead of block */
}
/* hover is trigger when we mouse over the A (anchor) tag and adjust the
	background position of the sprite to make it appear the button is down */
#rollover:hover {
	background-position: 0 -32px;
}
</style>

HTML Code

Next the html A (anchor) tag we apply the rollover button style to.

<a href="#-" id="rollover"> </a>

Now when we mouse over, it will appear that the button is changing states. Image sprites aren’t only for buttons, but can be used for rollover menus, animations, or anything that has multiple display states.

Calculate Time Difference Between Your End User And Your Server

Overview

People access your site aren’t always in the same timezone as you are. Now perhaps you would like to determine what the time is for a user in a different country. Then here is a quick way to find this information out.

This example is very useful if you simply want to fetch your clients date and time or timezone; but also good to see what time of day (their time, not server time) your clients access your website.

Now before I should you the code, remember that PHP is server side code – ie. it runs on the server and as such doesn’t have access to the clients local time. Javascript however is client side code which means it can see the localtime but the servers time. So a combination of the two will allow us to calculate the difference.

How To Calculate Time Difference

The way the below example works, is that the client will click a submit button which sets the value of the hidden input field to their local time stamp and that gets submitted to the same php script. Then the php script checks if that value has been sent and if it has, then it gets the local time (of the server) and takes the clients times and shows a message depicting the difference.

<!DOCTYPE html>
<html>
<head>
	<title>Server and Client Time Example</title>
</head>
<body>
	<script type='text/javascript'>

	// when we submit the form, get the client time and submit it as the
	// hidden field 'client_timestamp'
	function getClientTime() {
		var d = new Date();
		// we divide the timestamp by 1000 to go from milliseconds to seconds
		var timestamp = Math.floor(d.getTime()/1000);

		// put the timestamp into hidden field to be passed with the form
		document.getElementById('client_timestamp').value = timestamp;
	}

	</script>

	<form method='post' id='myform' onsubmit='getClientTime();'>
		<input type='hidden' id='client_timestamp' name='client_timestamp' />
		<button type='submit'>Send My Time</button>
	</form>

	<?php

	// if the form with the timestamp was submitted
	if( isset( $_REQUEST['client_timestamp'] ) ) {
		// the time posted to this script through the form
		$client_time = $_REQUEST['client_timestamp'];

		$server_time = time();

		$client_string = 'Your clients time is: ';
		$client_string .= date('d F Y h:i:s A',$client_time);

		$server_string = 'Your server time is: '
		$server_client .= date('d F Y h:i:s A',$server_time);

		// display the times
		echo $client_string.'<br />';
		echo $server_string.'<br />';
	}

	?>

</body>

</html>

CSS Two Column Fluid Layout – Static Column With Elastic Fluid Column

Overview

Are you looking for some quick HTML code to create a two column table with one static column and an elastic or fluid column. It took me a while to figure out, especially since css is one of my weaker languages. So I have placed the code here to hopefully make your life easier when it comes to creating html static and liquid column layouts.
There are only two parts to achieve this and what you will find after creating the two pages (one css file and an html file) is a page that has a static right hand column of around 400px and a elastic, liquid left column (or main content) that will stretch to fit the width of the browser as you resize the window.

CSS Two Column Fluid Layout

Below is the css code used to create the two column table. The important part to take notice of is wrapper which has a 400px padding to the right. This allows the fixed right hand column to fit snug next to it without the right column dropping down below. Copy the below code into a separate css file (I named mine elastic.css) or include it inline in the same HTML file where the html code will be.
As you will see, there are some optional css parameters which are commented out. They are more for styling rather than being required. Use as needed.

body {
	font: 16px/24px Georgia, serif;
	color: #5A5A5A;
	margin: 0;
}

header, footer {
	/*padding: 30px 20px;  optional: add some padding to match the margins of the #wrapper */
	background: #555; /* optional: background colour */
	color: #F0F0F0;
}

#wrapper {
	padding-right: 400px; /* padding should be the total width of all right columns */
	/*margin: 0 20px;  optional: spacing to the side of our content and sidebars */
}

#content {
	float: left;
	width: 100%;
	min-width: 600px;
}

.sidebar {
	float: left;
	width: 400px;
	margin-right: -1000px;
	/*background: #DDD;  optional: background colour */
}

.sidebar .side-column {
	width: 200px;
	float: left;
	/*margin-left: 20px;  optional: add a small space between the columns as well as the content to the left */
}

footer {
	clear: left; /* clear the floating from the above content and sidebar this makes the footer appear correctly below */
}

HTML Code

Create your html file and paste the following code into it. If you decided to include the above css inline, then you will need to paste the above css code into the html code below.

<!DOCTYPE html>
<html>
<head>

<title></title>
<link rel="stylesheet" type="text/css" media="all" href="elastic.css" />

</head>
<body>
	<header><strong>Our Header</strong></header>
	<div id="wrapper">
		<div id="content">
			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam auctor interdum elit faucibus scelerisque. Curabitur eleifend orci eget ante egestas viverra ac nec mauris. Pellentesque et dolor et leo pellentesque sollicitudin vitae vel velit. Phasellus ullamcorper sapien in sapien fermentum viverra. Sed dignissim est nec risus elementum molestie. Morbi placerat pharetra massa vitae aliquam. Curabitur laoreet suscipit leo, sit amet lacinia dolor placerat eu. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla facilisi. Nulla lacinia, ante ac dignissim viverra, nunc orci rhoncus odio, porttitor aliquet orci massa non lorem.
		</div>
		<div class="sidebar">
			<div class="side-column">
				Sed ornare sollicitudin nisi, in tristique quam laoreet non. Nullam semper, turpis et pulvinar pulvinar, quam dui consequat mi, ac aliquet arcu nunc id massa. Vivamus aliquam odio eget neque auctor tempus sollicitudin dui malesuada. Suspendisse tincidunt eleifend pellentesque.
			</div>
			<div class="side-column">
				Phasellus arcu nulla, pulvinar et cursus id, venenatis ac augue. Sed vitae erat in ante tristique cursus at non ante. Ut auctor metus at neque consectetur pulvinar. Morbi et mauris odio. Nulla viverra vulputate leo, vitae porta augue aliquam ac. Praesent ut nisi velit.
			</div>
		</div>
	</div>
	<footer><strong>Our footer</strong></footer>

</body>
</html>

After having created your two files, a css file and a html file, you can open the html file to see the result. You will notice that there are two columns in the html file, one being static/fixed width to the right hand side and the main content being liquid and is resized as the browser window is resized. It is a great way to make the most of your web browser window space and is rather simple to use (once you have the code samples).

CSS Padding vs Margin – Whats the Difference?

CSS Padding vs Margin – Whats the Difference?

When cutting up a design into html, you will need to recreate the design in html as accurately as possible. Positioning the elements correctly in html (not to mention, that dreaded cross browser support) can be tricky and having the elements laid out accurately can be the difference between a good looking website and a great looking website. To achieve this you will need to add a bit of div padding or div margins in order to get a div tag aligned into the correct place.

What is the difference between CSS Padding vs Margin

You may wonder what the differences between padding in html and margins in html really are. To give an analogy, think of a cardboard box (that represents your div tag). Now you want to place something inside the box, lets say a vase (in this case, the vase represents the contents inside the div tag, such as text, images or other web content). Now to position the vase correctly inside the box, we would add some newspaper “padding” into the box to hold the contents of the in its positions. The more padding you add, the less space there is in the box for the vase to move.

Now html margins is more like the space around the cardboard box. The more margins you add around the box, the further away it would space other boxes from itself. Larger margins means more space around the box. If you have no space (or html margins), then other boxes will be positioned right next to it.

When to use CSS Margin and CSS Padding

If you wanted to position the contents inside of a div (or any html tag) you will use padding (or newspaper as our previous analogy would depict). However if you wanted to position the div tag (which includes its contents inside), you will use margins.

That is a bit of a long winded description, but hopefully that will correctly explain what the differences are between html padding and margins.

Summary

Basically, when it comes to padding vs margins, your margins are just the space around an element and padding is the space inside an element. Padding being the space inside and Margin being the space around the outside.

2D Sprite Animation Tutorial

What are sprite animations?

A sprite animation is basically a large image which contains a whole bunch of smaller images. Think of it as a film strip where each frame is the next piece of animation in the sequence. The idea of sprites is that you only need to load one image and it will contain all the smaller images needed to create the animation. You simply position the background position of the sprite and it will appear to animate the sprite. For more information on sprites, check out the css button sprite tutorial.

End Result Demonstration


Above is the finished example of a flame sprite and it is what this tutorial will show you. As you can see it appears as an animation, however we simply move the background position of the larger image to create the illusion of movement.

Why should you use sprites?

Before images and css items can be displayed on your webpage, your browser must request the item such as javascript files, images, css files, etc. Each request takes time and your browser must wait for a response and then download the file for it to be displayed. So in short, the less items means less time to request and download items, meaning less time to load a page. So using sprites will increase the speed at which your website loads.

Flame Ball Sprite

2D Sprite Animation Tutorial

Above is the large flame sprite image I am using to create the sprite animation for this tutorial. We use javascript to move the background position of the sprite image. In the below example, we do this every 100ms. To achieve smooth animation, we would need to achieve 25 frames per second, however this would increase the size of the sprite image, so we will do it a time frames per second.

Now for the code to get this all working

CSS Code

<style type="text/css">

#flameanimation {
	/* our flame sprite png */
	background: url(http://www.example.com/images/flamesprite.png);
	width: 512px;
	height: 512px;
}

</style>

Javascript Code

Here is a quick javascript function to move the background position of the sprite animation to the next frame. We start at frame 1 and for each frame of animation we move 512px to the left since each frame is 512px wide by 512px high. Moving the background image positions every frame creates the illusion of movement, just as a movie is made up of 25 or 29 frames in a second.

<script type='text/javascript'>

$(document).ready(function(){
	// call the next() function every 100 ms.
	setInterval(next, 100);
});

// first frame of animation
var frame = 1;

// move the sprite animation to the next frame
//	i.e. move background position to the next image in the sequence
function next()
{
	// Set the position of the sprite image 512px more to the left on each frame.
	var left = 512 * frame;
	// top stays 0 since all the images have Y positioned at 0
	var top = 0;
	document.getElementById('flameanimation').style.backgroundPosition = '-'+left+'px -'+top+'px'; 

	frame++;
}

</script>

HTML Code

Next we create the div tag where the sprite animation will be applied to.

<div id="flameanimation" title="Sprite Animation"></div>

Now as the javascript next() function runs, it will move the background image to the left which will create the illusion of animation.

flame sprite image obtained from http://forum.unity3d.com/threads/60284-Free-2d-sprite-animations.

Pass a PHP Array to Javascript as JSON using AJAX and json_encode

Overview

You will mostly likely (or already have) reached a point where you have a PHP array and you need to be able to access that array from inside a Javascript function. You may wonder if it is possible to pass an array from PHP to Javascript. Fortunately I have created a tutorial on how this can be achieved. Below I will show you how to Pass a PHP Array to Javascript as JSON using AJAX. There are two parts to accomplish this task.

Creating The PHP Array

Firstly you need a PHP script which has the PHP array you want to pass back to Javascript. You encode the array into a JSON string using the PHP function `json_encode()`. We then echo the string into the PHP file to make it accessible to the AJAX function calling this script.

Call The PHP Script That Contains The PHP Array

Secondly we create an HTML which will contain the AJAX function to call the PHP script. We will use the jQuery `$.getJSON` function which converts the output from the PHP function ‘json_encode()’ into a JSON object. Once we have the JSON object, we can loop through it and use it as we require. We don’t really need to convert the JSON array to javascript array since we use jQuery’s ‘$.each()’ function to loop through the JSON array that is returned.

Pass a PHP Array to Javascript as JSON using AJAX

Below is the code that is to be placed into the PHP script. This file will be called by the jQuery `$.getJSON` function.

<?php

/* set out document type to text/javascript instead of text/html */
header("Content-type: text/javascript");

/* our multidimentional php array to pass back to javascript via ajax */
$arr = array(
	array(
		"first_name" => "Darian",
		"last_name" => "Brown",
		"age" => "28",
		"email" => "darianbr@example.com"
	),
	array(
		"first_name" => "John",
		"last_name" => "Doe",
		"age" => "47",
		"email" => "john_doe@example.com"
	)
);

/* encode the array as json. this will output [{"first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr@example.com"},{"first_name":"John","last_name":"Doe","age":"47","email":"john_doe@example.com"}] */
echo json_encode($arr);

?>

Javascript / HTML Code Snippet

Place this code into a file with the extension `.html`. The below code will call the above PHP script using AJAX and the jQuery function `$.getJSON`. The PHP script will have the PHP array encoded as a json string. Once the `$.getJSON` function returns, the Javascript function will have access to the PHP array that has been converted into a JSON object.

<html>
<head>
	<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>

	<!-- this UL will be populated with the data from the php array -->
	<ul></ul>

	<script type='text/javascript'>
	$(document).ready(function(){
		/* call the php that has the php array which is json_encoded */
		$.getJSON('json_encoded_array.php', function(data) {
			/* data will hold the php array as a javascript object */
			$.each(data, function(key, val) {
				$('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>');
			});
		});

	});
	</script>

</body>
</html>

 

Passing variables to PHP using JSON and AJAX

If you would like to pass some variables to PHP you can change the parameters as shown above. In my example below, I pass the variables name and age and then the PHP function could use these to search a database or file for that person and then return that specific information as a JSON array.

$.getJSON('json_encoded_array.php', {name:'Darian Brown',age:40}, function(data) {
	// ... handle response as above
}

How To Abort A Previous Ajax Request In jQuery

Overview

When using ajax to request a page or data, there will be occasions where you will need to cancel the ajax call. I found this useful after building a search as you type feature and I would abort the previous search and request a new ajax search each time they typed a new letter. Since their old word has changed to a new meaning, completing the old request is meaningless since the new word is an entirely different category. For example the typed fee and then they type `d` making the word feed. So I would abort a previous ajax request in jquery and issue a new ajax search on feed.

Additional uses for aborting an ajax request in jquery

Another reason may be that the page you are calling enters an infinite loop and stops the call from returning. Maybe you need to cancel a previous request before making a new request to prevent duplicate requests from being sent.

How To Abort A Previous Ajax Request In jQuery

Luckily jQuery has made this almost too easy as you can see by my example below.

/* our handler to the ajax request */
var xhr = null;

function goAjax()
{
	/* if there is a previous ajax request, then we abort it and then set xhr to null */
	if( xhr != null ) {
		xhr.abort();
		xhr = null;
	}

	/* and now we can safely make another ajax request since the previous one is aborted */
	xhr = $.ajax({
		type: "POST",
		url: "/some/url",
		data: "variables=whatever&var2=something",
		success: function(msg) {
			/* handle the ajax response */
		}
	});
}

Now you can call the goAjax() function as often as you like and it will cancel the previous ajax request if it hasn’t been completed before making a new request preventing duplicate requests from stacking up.

<a href='javascript:goAjax();'>Click me as much as you like</a>

And that is all there is to it. Simple and straightforward.

Specify Favicon.png In Html

Overview

Favicons are the tiny icons that usually appear next to the url in your browser. Favicons add a nice flair to your site and they are typically easy to implement.

specify favicon.png in html

Image showing an example of a favicon in showing in google chrome

Compatibility

For compatibility with all browsers stick with .ico is the way to go, however png favicons are support by most modern browsers. You can also specify both a favicon.png and favicon.ico in your html code to ensure complete compatibility.

Specify Favicon.png In Html

To specify favicon.png in html all you need to do is include the following line in the head of your html.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="icon" type="image/png" href="http://www.thecave.info/favicon.png" />
  </head>

Why use favicon.png

I have found that is it usually easier to save an image as a png as opposed to ico. Additionally, a png can be smaller than ico. There are other websites that will allow you to upload an image and convert it to an ico should you wish to have both a ico and png version of your favion.

Overlay HTML Over Flash Object

Overview

When building websites that use HTML and Flash, you may find that the flash movie appears above all of your other content such as drop down menus, div boxes and shadow-boxes. It can happen even when you manually enter in the z-index of those elements.

A Note About Z-Index Layering

The z-index of an item determines the layer an item will be rendered on. The higher the z-index number, the closer to the top layer an item will appear. So an item with a z-index of 10 will appear in front of an item with a z-index of 9.

Setting The Z-Index Of An Item

<style>

.your-item {
    z-index: 1000; /* or what whatever number you like */
}
</style>

Overlay HTML Over Flash Object

It can be very frustrating when flash appears above html content and menu. The reason this occurs is that DHTML uses layers to decide which elements stack in front of others. Just as a stack of cards are layered on top of each other. Content like Java or Flash that is embedded into the page ignores the layer order and is by default rendered on the highest layer of the page.

Older browsers are still stuck with this issue but luckily most modern browsers these days have the ability to layer the embedded content along with the rest of your elements. All you need to do to overlay html over flash object is to set the `WMODE` parameter to `transparent` and now it will obey your layering order which is controlled by the swf’s z-index. Other values for WMODE are ‘window’ (default), ‘opaque’, or ‘transparent’.

I will show you two ways on how to enable WMODE when embedding flash in your website.

1st option – Inline Embedding

To set the `WMODE` you need to set it in two place which I have highlighted yellow in the below example.

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="380" height="190" id="YourFlashMovie" align="middle">
	<param name="allowScriptAccess" value="sameDomain" />
	<param name="allowFullScreen" value="false" />
	<param name="movie" value="AS3_File_Upload2.swf" />
	<param name="quality" value="high" />
	<param name="wmode" value="transparent" />
	<param name="bgcolor" value="#333333" />
	<embed src="YourFlashMovie.swf" quality="high" wmode="transparent" bgcolor="#333333" width="380" height="190" name="YourFlashMovie" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>

Now all you need to do is place the flash movie where you want it and optionally set z-index to override the layer it appears on.

2nd option – swfobject (javascript include function)

Alternatively, you can use swfobject and specify similar parameters to acheive the same effect. Swfobject is a javascript file available free from http://code.google.com/p/swfobject/ and can be used to simplify the process of embedding flash into your website.

After downloading the swfobject.js from google code, include it into your page using.

<script type="text/javascript" src="swfobject.js"></script>

And then execute the function as shown below but ensure that you set the param to include `WMODE` as highlighted yellow.

<script type="text/javascript">

var flashvars = {};
var params = {wmode:'transparent'};
var attributes = {};

// divContainer is the div block that will then hold the embedded flash object.
swfobject.embedSWF("flashFile.swf", "divContainer", "300", "120", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

</script>

Prevent Menu From Appearing Behind Flash Object

Once you have completed the above, you can now change the order/layer the flash appears in your page. Your flash object should now obey the layer ordering and setting the z-index on both your flash object and menu should do the trick

Remember: The higher the number, the higher the layer. Higher layers appear on top of lower layers.

<style>

#YourFlashMovie {
    z-index: 1000; /* or what whatever number you like */
}

.yourMenuContainer {
    z-index: 1001; /* or any number as long as it is higher then #YourFlashMovie */
}

Display Disk Free Space Percentage In PHP

Overview – Display Disk Free Space Percentage In PHP

Have you ever needed a nice little progress bar on your website to display disk space free percentage? This can be handy if you would like to give your clients an indication on how much disk space free they have on their own virtually hosted website, or perhaps you need a simple web interface to keep an eye out on your server health. In any case, this progress bar will accurately show you how much disk space free and disk space usage on your server.

Checkout out a follow up article called showing an alternate way to determine the total size of a folder using php.

End Result – What This Article Will Achieve

Get Total Directory Size In PHP

Get Total Directory Size In PHP

Once you have copied and implemented the code shows in the 3 steps, you should have a tidy progress bar that will show you your disk usage on your server. Below is an image of what it should look like if you have followed the steps correctly.

 

Step 1 – PHP Code

Place this code into a PHP script inside the web directory of your choice. All three steps can be included into the same PHP file or seperated if requried.

<?php

/* get disk space free (in bytes) */
$df = disk_free_space("/var/www");
/* and get disk space total (in bytes)  */
$dt = disk_total_space("/var/www");
/* now we calculate the disk space used (in bytes) */
$du = $dt - $df;
/* percentage of disk used - this will be used to also set the width % of the progress bar */
$dp = sprintf('%.2f',($du / $dt) * 100);

/* and we formate the size from bytes to MB, GB, etc. */
$df = formatSize($df);
$du = formatSize($du);
$dt = formatSize($dt);

function formatSize( $bytes )
{
	$types = array( 'B', 'KB', 'MB', 'GB', 'TB' );
	for( $i = 0; $bytes >= 1024 && $i < ( count( $types ) -1 ); $bytes /= 1024, $i++ );
		return( round( $bytes, 2 ) . " " . $types[$i] );
}

?>

Step 2 – CSS Style Sheet

Place this code into a CSS style sheet inside the web directory of your choice. The CSS code can be included into the same PHP file created in step 1 or seperated into its own CSS file if required, however since it is executing php code to create the width of the element, it should not be placeed inside a separate css file.

<style type='text/css'>

.progress {
	border: 2px solid #5E96E4;
	height: 32px;
	width: 540px;
	margin: 30px auto;
}
.progress .prgbar {
	background: #A7C6FF;
	width: <?php echo $dp; ?>%;
	position: relative;
	height: 32px;
	z-index: 999;
}
.progress .prgtext {
	color: #286692;
	text-align: center;
	font-size: 13px;
	padding: 9px 0 0;
	width: 540px;
	position: absolute;
	z-index: 1000;
}
.progress .prginfo {
	margin: 3px 0;
}

</style>

Step 3 – HTML Code Including the Progress Bar

Place this code into an HTML file inside the web directory of your choice. The HTML code can be included into the same PHP file created in step 1 or seperated into its own file if required.

<div class='progress'>
	<div class='prgtext'><?php echo $dp; ?>% Disk Used</div>
	<div class='prgbar'></div>
	<div class='prginfo'>
		<span style='float: left;'><?php echo "$du of $dt used"; ?></span>
		<span style='float: right;'><?php echo "$df of $dt free"; ?></span>
		<span style='clear: both;'></span>
	</div>
</div>