Easy HTML5 placeholder fix (for unsupporting browsers)

In case you’d like to use the fancy HTML5 placeholder attribute for your input fields, but are afraid that certain, more “rusty” users, might not see it, since they don’t use HTML5 ready browsers, there’s a quick workaround that will enable the same effect to those who don’t support the original.

It’s built on top of Mootools (basic distribution), so you might want to load that, in case you don’t already use it (why???), and it goes like this:

function supportsPlaceholder(){
// Returns true or false, depending if it finds the “placeholder” attribute within your browser’s “input” object’s attributes
var i = document.createElement(‘input’);
return ‘placeholder’ in i;
};

window.addEvent(‘domready’, function(){
// Again, on domready event, so all the input objects are loaded and could be parsed

if(!supportsPlaceholder()){
// The current browser doesn’t support the input placeholder, so let’s add it dynamically
$$(‘input’).each(function(input){
if(input.get(‘placeholder’)){
// This input field has the placeholder parameter set up – Mootools recognizes it!
input.value = input.get(‘placeholder’);

input.addEvent(‘focus’, function(){
clearPlaceholder(this);
});

input.addEvent(‘blur’, function(){
if(this.value.trim()==”){
this.value = this.get(‘placeholder’);
};
});

input.getParent(‘form’).addEvent(‘submit’, function(){
// So you don’t submit the placeholder’s value
clearPlaceholder(input);
});

window.addEvent(‘unload’, function(){
// So it doesn’t end up pre-filled in the field – in some browsers
clearPlaceholder(input);
});
};
});

function clearPlaceholder(input){
if(input.value==input.get(‘placeholder’)){
input.value = ”;
};
};
};

});

And that’s it! If you embed the above code into your page, it should display correctly any input field you might have assigned placeholder attributes to, in any browser (well, I don’t know about ANY browser, but the most usually, modern ones, that still don’t support the placeholder, will do now!).

Bulletproof client-side form validation

In case you use the Mootools library (who doesn’t!) – and even if you don’t, I’ll share below a piece of code we’re using for automatically validating any form we use in our projects, simple and clean.

For now, it checks for empty fields that are required, for identical-value fields (to be identical) and for certain file type input values (images, documents or generic files). Whenever any of these conditions are not met, it will turn the corresponding form field’s border in red.

And now, for the code. First, the JavaScript:

window.addEvent(‘domready’, function(){
// Only add if after the page load, so it could find all of the .validate CSS class forms
$$(‘form.validate’).addEvent(‘submit’, function(e){
// Capture the “submit” form event
var focused = false;

this.getElements(‘.mandatory’).each(function(field){
// Checks for the .mandatory CSS class fields
if(field.type==’radio’ || field.type==’checkbox’){
if(!field.checked){
var skip = false;
if(field.type==’radio’){
// Check if other radios with the current one’s name aren’t checked
$$(‘input[name=' + field.name + ']‘).each(function(fieldSibling){
if(fieldSibling.checked){
skip = true;
};
});
};

if(!skip){
field.addClass(‘mandatoryAlert’);
if(!focused){
field.focus();
focused = true;

e.stop();
};
};
}else{
if(field.hasClass(‘mandatoryAlert’)){
field.removeClass(‘mandatoryAlert’);
};
};
}else{
if(field.value.trim()==”){
field.addClass(‘mandatoryAlert’);
if(!focused){
field.focus();
focused = true;

e.stop();
};
}else{
if(field.hasClass(‘mandatoryAlert’)){
field.removeClass(‘mandatoryAlert’);
};
};
};
});

var duplicateValue;

this.getElements(‘.duplicate’).each(function(field){
// Checks for identical-value fields (for example, the “password” / “check password” fields)
if(!duplicateValue){
// Set the first value of the duplicate fields, to be compared with the next values
duplicateValue = field.value.trim();
}else{
if(field.value.trim()!=duplicateValue){
field.addClass(‘mandatoryAlert’);
if(!focused){
field.focus();
focused = true;

e.stop();
};
}else{
if(field.hasClass(‘mandatoryAlert’)){
field.removeClass(‘mandatoryAlert’);
};
};
};
});

this.getElements(‘input[type=file]‘).each(function(field){
// Checks the file type input fields for certain file types to be uploaded, like images, documents and generic files
if(field.value.trim()!=”){
var imageComponents = field.value.trim().split(‘.’);
var extension = imageComponents[imageComponents.length - 1];

if(field.hasClass(‘image’)){
// Let’s validate (superficially) the selected file to be an image one
if(extension!=’jpg’ && extension!=’jpeg’ && extension!=’gif’ && extension!=’png’ && extension!=’bmp’){
field.addClass(‘mandatoryAlert’);
if(!focused){
field.focus();
focused = true;

e.stop();
};
alert(‘This field only supports image type files!’);
};
};

if(field.hasClass(‘document’)){
// Let’s validate (superficially) the selected file to be an “document” (.doc, .xls, .ppt, .pdf)
if(extension!=’doc’ && extension!=’xls’ && extension!=’ppt’ && extension!=’pdf’){
field.addClass(‘mandatoryAlert’);
if(!focused){
field.focus();
focused = true;

e.stop();
};
alert(‘This field only supports .doc, .xls, .ppt or .pdf type files!’);
};
};

if(field.hasClass(‘file’)){
// Let’s validate (superficially) the selected file to be an “file” (.doc, .xls, .ppt, .pdf, .zip, .rar)
if(extension!=’doc’ && extension!=’xls’ && extension!=’ppt’ && extension!=’pdf’ && extension!=’zip’ && extension!=’rar’){
field.addClass(‘mandatoryAlert’);
if(!focused){
field.focus();
focused = true;

e.stop();
};
alert(‘This field only supports .doc, .xls, .ppt, .pdf, .zip or .rar type files!’);
};
};
};
});
});
});

Hopefully, the embedded comments will be explanatory enough.

Next, you need to define the .mandatoryAlert CSS class like so:

.mandatoryAlert {
border-color: #f00 !important;
}

And that’s about it! If you have loaded, before the above script, the Mootools library (it works with a pretty minimal distribution, or you could go with Google’s full-sized hosted one – at http://code.google.com/apis/libraries/devguide.html#mootools ), and have set the right classes to your form and form elements (that is, the “validate” class to the form, and “mandatory”, “duplicate” or “image” / “document” / “file” – the last three only for file type input fields – to the form fields you’re interested in validating), you should have an auto-validating form upon submission.

Obviously, this could be relatively easy translated for any other library (Prototype, jQuery, etc.). But since I’m a fan of Mootools… you’re stuck with this one, for now! :-D

Have fun, and feel free to send feedback on your implementation.

Automatically compress local JavaScript files (on an Apache server)

One of the most recommended (and easiest to implement) techniques for web pages optimization is compressing the CSS and JavaScript files used.

While this is not a particularly difficult thing to do manually (for example, using the YUI compressor found here), when releasing a new version on the live server, it would be much easier to use an automated method that allows you to write the JavaScript in your own development style (using comments and a more loose formatting), and serve it directly compressed to the browser, on request.

Well… wonder no more! We’re going to present an easy and bullet-proof method of doing just that, on an Apache web server. For this purpose, we’re going to use Dean Edwards JavaScript’s Packer class, more precisely its PHP version, “translated” by Nicolas Martin.

You’re going to have to add it to your JavaScript folder (assuming you have such a folder in your project, otherwise… add it in your common folder, or… wherever you want). In the same folder, you have to add an index.php file that will load this PHP class and use it to dynamically compress your JS files.

The content of the JS folder’s index.php file should be something like

if(!empty($_GET['script']) && is_file($_GET['script'] . ‘.js’)){
require_once ‘/relative/path/to/JavaScriptPacker.class.php’;

$script = file_get_contents($_GET['script'] . ‘.js’);

$packer = new JavaScriptPacker($script, 62, true, false); // Default configuration
$script = $packer->pack();

header(‘content-type:application/javascript’);
echo $script;
}

This, as you may notice, will receive a script parameter (type GET) and, if it will fit a file in your JS folder named as its value (plus the .js extension), will compress and output it.

In order to automatically call the index.php page with the JS file’s name (without the .js extension), you need some .htaccess commands. These are:

Options All -Indexes # Disabled direct access to your JS folder’s content

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /path/to/your/JavaScript/folder/

RewriteRule ^(.*)\.js$ ?script=$1 [L] # Here you instruct the server to pass any JS file called directly, to index.php as its script parameter
</IfModule>

As you may see, you must have the mod_rewrite module installed and active for this method to work.

If you have followed and understood all of the above… you now should access ONLY compressed JS files when calling them directly from your address bar (for example, try accessing http://your.domain.name/path/to/your/js/file.js – you should see something beginning with

eval(function(p,a,c,k,e,d){ …

So… that’s it! You now serve compressed (and somewhat “encoded”) JavaScript files, thus minimizing the traffic and the time needed for the browsers to load your scripts.

One way of seeing the effects of this change is using either Page Speed or YSlow Firebug plug-ins. Try testing your web page without this compression method, and then, with it enabled. Depending on the size of your original script(s), you should be able to increase your ratings between 2-3 and up to 10 points.

Of course, you could go one step further, and try concatenating all of your scripts (in case you use more than one – and this is usually the case), and THEN compress it – you should gain up to 15 points in the performance rankings. But… I’ll let you do that yourselves. :)

Using custom fonts in web

Have you ever wanted to use custom, “fancy” fonts (like the ones you have installed yourself on your system, or your designer may have used in some slick layout), in your web pages, but were forced to use images of that writing, instead? Well, whine no more…

Today I’ll give you a short (but comprehensive) insight into how you can build-in custom fonts into any webpage. It’s only a matter of CSS (and its less-familiar @font-face syntax). That is,

@font-face {
font-family: ‘Custom family name’;
src: url(‘/path/to/customfont.eot’);
src: local(‘Full System Custom Font Name’), local(‘PostScript Custom Font Name’), url(‘/path/to/customfont.ttf’);
}

So what does all this mean? Well, the “@font-face” block allows you to define new font families (you know – the things that enable you to write with a certain font face in certain web page elements…). Its font-family property is where you define the new font family’s name (custom, of course, since your users will most probably not have your fancy font installed).

The first src property is meant for embedding the EOT type font. You will get such a font file, for your special fancy font, using a font converter, of course. The best I found is Font Squirrel, but there are others (both online and offline). You just upload in your existing font, and it will output any font you might need for different browser types (it even embeds the font into CSS, so you won’t have to walk around with different external font files). EOT (Embedded OpenType) is the only font format Internet Explorer recognize (so far), and it’s the only way of displaying custom fonts in IE (of course… it HAD to be “special”!).

The following src property is meant for overwriting the first one (by those browsers that use TrueType fonts – that is, everyone BUT Internet Explorer), and it uses a “normal” TTF type font as the custom font family face. The “local” parameters are used in case your visitors actually HAVE your font installed on their systems (they represent, correspondingly, the system’s font name, and the PostScript font name – for such browsers as Safari under OS X).

REMEMBER! Always use this order when declaring fonts (first Internet Explorer’s EOT type, then the other browsers’ TTF / OTF types), otherwise they will overlap, and you will only be able to see the custom font in Internet Explorer…

This being told… that’s it! You may now use this custom web font in any of your web page elements, just as

font-family: ‘Custom family name’, ‘Regular font’, etc…;

You can read more about embedding custom fonts in web pages here and here.

Building mobile websites (especially for iPhone)

Lately we were involved in some “mobile” projects, and since the iPhone is the most successful mobile device, we have focused mostly on developing “for” iPhone (this sounds almost as funny as those ’90s websites “optimized for Internet Explorer at 800×600 pixels”, huh? :P ).

So, if you’re also involved (or would like to be) in developing mobile websites, you should know some tricks that will make your “mobile programmer” life a bit easier.

First of all – the device. It’s kind of hard to build stuff that you cannot test periodically (and accurately), and owning an iPhone (or more) is not always possible. So… you need an emulator of some sort. And here comes Genuitec’s “iPhone Emulator for Windows” (as they call it) – MobiOne.

Personally I found it very user-friendly, complete and “honest” from the first test I’ve put it through. It’s true that it’s not a “complete” emulator (as Google’s Android one – that is quite a hustle to use, by the way) – meaning that you cannot install and test iPhone applications on it, but other than that… there’s nothing I can ask of it. It comes with an accelerometer emulator, some JavaScript libraries that could be used to interact with its “mobile functionality”, and since its latest version (milestone 6, at the time this article was written), it has even a “designer mode” (useful if you’re interested in drawing some iPhone-type interfaces for future projects – or for pitching on investors :D ). I’ll let you discover the rest of its functionality on you own…

Next: if you develop in php (as we do), you may also need a quick and reliable way of determining if the client accessing your website / web application comes from a mobile device or not. Well, we found that the “mobile_device_detect()” function from http://detectmobilebrowsers.mobi/ does this job brilliantly. It could be used very simple (just call the function and evaluate its response) or with various parameters, for very accurate results. Enjoy!

If you, as we did, find that the default mobile browser’s screen size is not enough for all your fancy web pages, you may use a nice trick to hide the browser’s address bar (well, you’ll save about 60 pixels in height!). Just add the

<meta name=”apple-mobile-web-app-capable” content=”yes” />

tag in your page’s head, and you’re all set. It doesn’t even mess up your valid HTML code :P

There are more tips and tricks related to mobile web development that we know and use, but… if you’re interested in more, ask us to write a “part two” on this topic. That’s it for now…!

Building a custom browser search engine

We’ll start this blog by presenting a neat trick: how to create and embed a browser search engine (you know, the box you see in the top-right corner of your [Mozilla Firefox or Internet Explorer] browsers), to be used for searching in any website that has a search capability.

First, you should have a basic understanding of programming (as in “what is a tag”, “what is a variable”, a “token”… those kinds of things) to follow this article.

So, if that is the case, start by creating a new XML-type document (in any text editor you like, even Notepad, Wordpad will do), and add the following lines:

<?xml version=”1.0″ encoding=”UTF-8″?>
<OpenSearchDescription xmlns=”http://a9.com/-/spec/opensearch/1.1/” xmlns:moz=”http://www.mozilla.org/2006/browser/search/”>
<ShortName>Your Search Engine Short Name</ShortName>
<Description>Your search engine’s description…</Description>
<InputEncoding>utf-8</InputEncoding>
<Image width=”16″ height=”16″ type=”image/vnd.microsoft.icon”>http://my.searched-website.com/theWebsitesIcon.ico</Image>
<Url type=”text/html” method=”get” template=”http://my.searched-website.com/?search={searchTerms}” />
<moz:SearchForm>http://my.searched-website.com/?search</moz:SearchForm>
</OpenSearchDescription>

Now, for what it all means. You should start, obviously, with an XML declaration.

Then, the OpenSearchDescription tag is simply a definition of the XLS document’s purpose (for the application trying to use the XML document). It shouldn’t bother you too much… just keep it that way!

The ShortName tag is the text you will see in the search box, as you should see by default “Google” or “Yahoo”. Try to keep it short.

The Description… to be honest, I don’t know where you use or will see this text. But as long as it’s in the “specs”… let’s keep it (and add a meaning to it).

InputEncoding represents the encoding of your search’s characters. I’m assuming you’re using the default English ASCII characters, so… also, keep it as it is. If you want to search using any other type of characters (latin, slavic, etc.), set the encoding correspondingly (if you know it :P ).

The Image tag holds your search engine’s icon (that you’ll see in the search box, after setting your engine as the default). I recommend you use the searched website’s favicon image (if applicable), else… don’t set it. You will see a default no-icon symbol.

The Url is the most important tag. It transmits the search query itself to the website you’re actually searching on. It has to contain that website’s search path, and as the search parameter you will use the predefined {searchTerms} token. You may set here how that website’s handling the searches (by GET or POST methods).

The moz:SearchForm tag is a Mozilla-specific tag, and it sets the search page’s main URL, to which it submits your search criteria.

So, this are the basic knowledge you’ll need to set up a custom browser search engine. Next, in order to install it in a browser’s search box, you’ll need another thing: to have a web page where to declare it, and from where to install it.

For this, you just need to add a simple line of code in the <head> section of any web page:

<link rel=”search” type=”application/opensearchdescription+xml” title=”Search my website using this fancy custom browser search engine” href=”http://my.own-webpage.com/mySearchEngineFile.xml” />

Of course, you need to modify (in both my code samples above) the “funny” values with real, proper ones. Once you did all that… the sky is the limit! :P Now you can search through any website in just one or two clicks (depending if you set your custom search engine as the default one or not :D ).

For a real-life example, we built an IMDb search engine, so we could search easily for movies. To install it, just one the search engines icons (by pressing the currently selected one’s icon), and select “Add MySearchEngine’sTitle” (or “Add Search Providers” > “My Search Engine’s Title” – depending on your browser). Try it yourself, if it sounds good!

This is not the “limit” of what can be done with custom browser search engines. For complete and detailed specs on using the OpenSearch format, follow this link: http://www.opensearch.org/Specifications/OpenSearch/1.1#OpenSearch_description_document