Best practices for modern Javascript development

Use the correct <script> tag

When you have to use some Javascript in an html file, you should always use the following



<script type="text/javascript">
    ... some JS code

But instead, how many times have you seen this when looking at the source code?

<script type="text/javascript" language="javascript">
    ... some JS code

In HTML, the


attribute is deprecated due to its redundancy with the


attribute. You should never use it anymore.

Keep your code in an external file

Using an external


file for your Javascript code is a lot cleaner than writing it in your html document, and it also allows the browser to cache the file, which will result in a faster website.

Put your Javascript code in a


file, then use the


tag in your html document to import the file:

<script type='text/javascript' src=''></script>

Don’t wrap code in HTML comments

In the 90′s some very old browsers weren’t able to interpret Javascript. In order to prevent unwanted results on those browsers, it was considered good practice in 1994-1997 to wrap Javascript code within html comments, so browsers with no Javascript support will simply ignore it.
Here is an example of some code wrapped within html comments:

<script language="JavaScript">
...some code

However, in 2010, all browsers (Even IE6, that means a lot) can interpret Javascript, so there’s absolutely no need to wrap code within comments anymore. Even worse, if code is wrapped within comments and use the decrement symbol


, you’ll expect some weird problems due to the fact the browser may think it’s the end of the html comment.

Use a framework

Unless your Javascript code is really short and easy, you should always avoid reinventing the wheel by using a framework of your choice. In my opinion, jQuery is the best and has an awesome community, so you should give it a try if you haven’t already.

Always declare your variables using var

You should introduce any variable you create with the


statement, otherwise it gets to the global scope. Also, using


makes your code more readable and self-explanatory.
Example of variable created using the



var name = "Jean";
var size = data.length;

Keep your code unobtrusive

Some years ago, when a programmer wanted to add an event to an html element (for example, if you want to validate a date when the user typed something) he simply put Javascript code in the html, using a special attribute such as






, etc.

<input type="text" name="date" onchange="validateDate()" />

This works great, but it is a bit dirty. HTML should only contain the document description. Just like it’s bad practice to use inline CSS styles, it’s bad practice to use inline Javascript.

Instead, what about using some unobtrusive Javascript? Using jQuery, it is pretty easy to do, as you can see in the following example:

	$('input[name=date]').bind('change', validateDate);

Include your scripts at the bottom of your HTML files

Not so long ago, it was generally considered good practice to insert your Javascript files within the




tags of your html document.
But browsers read html files from top to bottom, and load external files dynamically. Which mean that inserting scripts within the




tags will make your Javascript load before some of the page content.
In order to always load scripts after the content, Javascript files should always been included at the bottom of your html files, as shown below:

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

Use JSLint

JSLint is a web-app which takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate solution.
JSLint is great to find bugs in your code, and also things that may be written in a better way. This site is definitely my favorite coding buddy when developing some Javascript.

Don’t use document.write

The good old


method has been deprecated for years, however it is still very common to see it while browsing code.

document.write("hello world");

Instead of using this deprecated method, you should use the DOM and the


function to insert text on a page:

document.getElementById('hello').innerHTML('hello world');

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

Best practices for modern Javascript development

Tags: - - - - - - - - - - - - - - - - - - - - - - -

10 useful new WordPress hacks

Remove comments autolinks

If someone leaves a comment containing a url, the url will be automatically transformed to a link by WordPress. This can be useful, but personally I don’t like to see many links in comments, especially when they’re a bit spammy.
This is why I decided, on the latest CWC theme, to remove comments autolink. Doing so is pretty easy, just paste the following into your functions.php file. Once you saved the file, you’ll notice that autolinks have disappeared.

remove_filter('comment_text', 'make_clickable', 9);

» Source:

Automatically notify your users of new posts

If you run a private site using WordPress, then it could be useful to notify your users when a new post is published. The following snippet will get all user emails from your database and will send an email to them automatically when a post is published.
Of course, you shouldn’t use that code on your blog as it does not currently have any unsubscribe option.

function email_members($post_ID)  {
    global $wpdb;
    $usersarray = $wpdb->get_results("SELECT user_email FROM $wpdb->users;");
    $users = implode(",", $usersarray);
    mail($users, "New WordPress recipe online!", 'A new recipe have been published on');
    return $post_ID;

add_action('publish_post', 'email_members');

Twitter style “time ago” dates

Displaying dates using the “5 days ago” format is becoming very popular on blogs, thanks to Twitter popularity.
I have seen lots of complicated tutorials to use this format on your WordPress blog, however many people don’t know that WordPress has a built-in function to do the same thing:



Paste the snippet below anywhere within the loop, and it will display your dates using the “time ago” format.

Posted <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>

» Source:

Display post thumbnail in your RSS feed

Introduced in WordPress 2.9, the


function is very useful to easily add and display a thumbnail attached to a post. Unfortunately, there’s no built-in way to display this thumbnail on your RSS feed.

Happily, the function below will solve this problem. Simply paste it in your


, save it, and the post thumbnail will be automatically displayed on your RSS feed.

function diw_post_thumbnail_feeds($content) {
	global $post;
	if(has_post_thumbnail($post->ID)) {
		$content = '<div>' . get_the_post_thumbnail($post->ID) . '</div>' . $content;
	return $content;
add_filter('the_excerpt_rss', 'diw_post_thumbnail_feeds');
add_filter('the_content_feed', 'diw_post_thumbnail_feeds');

» Source:

Block external requests

By default, WordPress does some external requests in order to get the available updates and the WordPress news shown in your dashboard. Personally, I don’t mind them, but I’ve recently had clients who didn’t wanted any external requests. So, I’ve blocked them using this interesting hack.
Simply add the following line to your



define('WP_HTTP_BLOCK_EXTERNAL', true);

If you need to allow some external requests, it it easy to create a whitelist, as shown below:

define('WP_ACCESSIBLE_HOSTS', '');

This line of code have to be pasted in


as well.
» Source:

Easy debug mode

When things go wrong, you can always use the super useful WordPress debug tool,


. By default, you have to paste a line of code in your


to make the debug mode available.
By if you need to easily access the debug mode even when your site is live, you should edit your


file and replace

define('WP_DEBUG', true);


if ( isset($_GET['debug']) && $_GET['debug'] == 'debug')
  define('WP_DEBUG', true);

Once done, simply add a GET parameter to the url of the page you’d like to debug, as shown below:

Of course, for obvious security reasons you should replace the name debug by a random word of your choice so no one will ever see your site in debug mode.
» Source:

Use WordPress shortcode in theme files

WordPress shortcodes are a super easy way to add content such as rss feeds, google maps, galleries and more into your posts or pages. But what about being able to output shortcodes in your theme files?
A built-in function exists, but most people never heard of it. The function is called


. It takes one parameter, the shortcode you’d like to display. I’ve heard you can ad more than one shortcode as a parameter, but I haven’t tried it yet.


» Source:

Allow upload of more file types

If you ever tried to upload some not so common filetypes, such as Textmate’s


to your WordPress blog, you may have experienced an error, because WordPress simply doesn’t want you to upload some other file type.
Fortunately, you can add new file types to WordPress whitelist. Doing so is quite easy, just paste the following piece of code in your


, and you’re done.
Note that file types have to be separated by a pipe.

function addUploadMimes($mimes) {
    $mimes = array_merge($mimes, array(
        'tmbundle|tmCommand|tmDragCommand|tmSnippet|tmLanguage|tmPreferences' => 'application/octet-stream'

    return $mimes;

add_filter('upload_mimes', 'addUploadMimes');

» Source:

Google Docs PDF viewer shortcode

Google Docs is definitely the easiest way to read documents in .pdf, .doc or .xls online. So, if you want to share a PDF file with your readers, what about creating a shortcode that will open the PDF in Google Docs instead of forcing download?

Simply paste the code in your



function pdflink($attr, $content) {
	return '<a class="pdf" href="' . $attr['href'] . '">'.$content.'</a>';
add_shortcode('pdf', 'pdflink');

Once you saved the file, you’ll be able to use the shortcode on your posts and page. Here is the syntax:

[pdf href=""]View PDF[/pdf]

» Source:

Detect the visitor browser within WordPress

Well, this hack is not so new, but it still remains one of my favorites. What this code does is pretty simple, it detects the name of the visitor browser and adds it to the


That way, you can correct browser-specific problems extremely easily. The function has to be pasted in your



function browser_body_class($classes) {
	global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

	if($is_lynx) $classes[] = 'lynx';
	elseif($is_gecko) $classes[] = 'gecko';
	elseif($is_opera) $classes[] = 'opera';
	elseif($is_NS4) $classes[] = 'ns4';
	elseif($is_safari) $classes[] = 'safari';
	elseif($is_chrome) $classes[] = 'chrome';
	elseif($is_IE) $classes[] = 'ie';
	else $classes[] = 'unknown';

	if($is_iphone) $classes[] = 'iphone';
	return $classes;

The function output will look like:

<body class="home blog logged-in safari">

» Source:

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

10 useful new WordPress hacks

Tags: - - - - - - - - - - - - - - - - - - - - - - - - - - - -

8 CSS preprocessors to speed up development time

Less CSS

Less is probably the most well known CSS preprocessor. It allow a simplified syntax and the use of variables. Less CSS is for the Ruby programming language, however it looks like Aaron Russel created an extension for creating cached stylesheets your PHP projects can use.

Get it:


On their website, Sass claims to make CSS fun again. To be honest, I must admit that what this project is capable of is very interesting. Like Less CSS, it allow the use of variables and have a simplified syntax. Sass is definitely a great tool, unfortunely only available for Ruby, as far as I know.

Get it:


If like me, you’re a PHP Lover, here is a css preprocessor made for your favorite language. I haven’t tested it yet, but Turbine looks very cool. It allow a minimal syntax, automatically gzip multiple css, fix cross-browser issues, and a lot more. A must check if you’re into PHP.

Get it:

Switch CSS

Switch is a full featured, production ready CSS preprocessor. It runs under Apache with mod_python, or as an environment-agnostic command line tool.

Get it:

CSS Cacheer

CSS Cacheer is a very cool preprocessor which allows developers to create plugins. It requires PHP and Apache with mod_deflate and mod_rewrite in order to work.

Get it:

CSS Preprocessor

Another interesting preprocessor, written in PHP 5. Among other things, this tool allow you to use expressions such as margin-left: (200px * 3/2 – 10px); in your stylesheets.

Get it:


DtCSS speeds up CSS coding by extending the features to CSS. Such as nested selectors, color mixing and more. DtCSS reads the CSS file with special syntax written for DtCSS, and outputs the standard CSS. It also comes with a smart caching system.

Get it:


Unfortunely, CSS PP is still in alpha status, but the authors says the code will be released very soon. One of the good points of this projects is that it will be available in PHP, Python and Ruby. Great news for developpers who work with all of these languages.

Get it:

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

8 CSS preprocessors to speed up development time

Tags: - - - - - - - - - - - - - - - - - - - - - - -

Google Docs may soon offer cloud printing, device syncing

Blog site reveals source code behind Google Docs showing that cloud printing, device syncing, and third-party apps may be coming soon.

Tags: - - - - - - - - - - - - - - - -

VLC Makes Its Way to the iPhone, iPod Touch

VLC has made its way fully onto iOS with this week’s release for the iPhone and iPod Touch. The open-source, multi-platform video player will allow Apple’s mobile device users to play a number of different video formats, from DiVX to AVI and more.



This latest version of VLC works on the iPhone 4 and 3GS, as well as the iPod Touch 3rd and 4th generation. This version of VLC allows users a greater flexibility by providing support for more file types as well as allowing them to delete files directly from the app, rather than resorting to using iTunes on their computer.

The app first broke onto iOS in late September with an iPad app, surprising many. As we mentioned when the iPad app was approved, it seems that after Apple clarified its App Store guidelines, it moved to a more liberal policy.

9 to 5 Mac took a look at the app and offered up an early review of the features, which you can see below.

VLC 1.1.0 is available in the App Store.


Tags: - - - - - - - - - - - - - - - - - - - - -


Moovida Media player The application that plays all existing audio and video formats! Moovida is a free efficient and light multimedia center. The software is completely optimized for low performance PC. It doesn’t require much memory resources and operates perfectly in family computers!

Author: MediaApp
Duration: 62
Published: 2010-09-15 12:28:34

Tags: - - - - - - - - -

India Government Unveils Android Tablet Prototype Cloud Computer predicts $10 to 1.2 Billion People

NEW VIDEO WITH SPECS HERE PLEASE SHARE AND EMBED UPDATED GLOBAL NEWS WORD ON THE STREET RUMOR IS TO BE ANDROID BASED India Government Unveils Android Tablet Cloud Computer $10 may go to 1.2 Billion People in India Computers Internet Computing Breaking Global News Worldwide World Unnamed prototype possible code name Karma unnamed device prototype dropping to $20 and possibly getting as low as $10. Android Linux-based computer tablet Web browser multimedia player PDF reader Wi-Fi camera cameras webcam video conferencings2GB of RAM and on the cloud plus memory card and USB ports utilizing YouTube for education and social networking Indian Institute of Technology co-design motherboards Low Cost access –Cum-Computing Device Unveiled by Shri Kapil Sibal 17:31 IST The Union Minister for human Resource Development, Shri Kapil Sibal unveiled a low cost computing-cum-access device, here today. The price of the device exhibited today is expected to be around $35 per piece, gradually dropping down to $20 and ultimately to $10 a piece. Since this effort of continuous reduction in price and enhancement in capabilities would require a constant endeavour for R&D, IIT Rajasthan and some other IITs and technical institutions are setting up research teams to cover a wide range of issues in achieving our ultimate goal in terms of price and quality. The three cardinal principles of the Education Policy viz., access, equity and quality could be served well by providing

Duration: 215
Published: 2010-07-24 05:39:26
India Government Unveils Android Tablet Prototype Cloud Computer predicts $10 to 1.2 Billion People

Tags: - - - - - - - - - - - - -

Sprint 4G App Challenge accepting Android submissions

With Sprint (NYSE:S) continuing to roll out its 4G WiMAX network across the U.S., the operator launched its first Sprint 4G App Challenge, calling on developers to create applications that leverage next-generation data speeds as well as the unique features of smartphones like the Android-based HTC Evo 4G and Samsung Epic 4G. Sprint is accepting submissions now through Nov. 5, and will recognize the most impressive entry in each of five categories: Entertainment, Gaming, Productivity, Social Networking and Multimedia. Submissions will be judged based on four criteria–creativity, intuitive navigation, functionality and design–and winners in each category will walk off with a $50,000 grand prize, an HTC Evo 4G with one year of Sprint service and a one-year membership to the Sprint Professional Developer Program (including 250 hours in the Virtual Developer Lab).

Sprint recommends that developers learn more about building 4G applications by checking out the Sprint Applications Developer Program website, which includes resources on developing for an Android handset and maximizing the Sprint 4G network as well as the HTC EVO 4G and Samsung Epic 4G’s hardware and software capabilities. Sprint adds that developers who submit 4G App Challenge submissions by Oct. 20 will be eligible to receive one free admission to this year’s Sprint Developer Conference, taking place Oct. 26-28 in Santa Clara, Calif.

For more on the Sprint 4G App Challenge:
- read this release

Related articles:
issues 4G developer guide in advance of HTC Evo
adds GetJar’s free mobile apps catalog
expands open location platform

Tags: - - - - - - - - - - - - - - - - - - - - - - - - - - -

Android Market tops 80,000 apps–BlackBerry App World at just 10,000

Days after Apple (NASDAQ:AAPL) announced its App Store now features more than 250,000 iOS-based mobile applications, rivals Google and Research In Motion (NASDAQ:RIMM) have checked in with inventory updates on their own storefronts: Android Market now boasts more than 80,000 applications, while BlackBerry App World stands at over 10,000. Google updated Android Market’s status in conjunction with the introduction of T-Mobile USA’s new Android-powered G2 smartphone–the store has added 10,000 new apps since mid-July. Google vice president of engineering Andy Rubin credited Android’s open-source ethos for fostering developer interest in the platform: “Developer-led Android innovation is flourishing,” he said in a prepared statement. “On Android Market alone, the number of applications available to consumers has grown from just 50 applications two years ago to more than 80,000 applications today.”

But access to Android Market is not available to all devices running the Android OS. Hugo Barra, Google’s director of products for mobile, said that Android 2.2 (a.k.a. ‘Froyo’) is not optimized for use on tablets, adding “The way Android Market works is it’s not going to be available on devices that don’t allow applications to run correctly. If you want Android Market on that platform, the apps just wouldn’t run–[Froyo] is just not designed for that form factor. We want to make sure that we’re going to create an application distribution mechanism for the Android Market, to ensure our users have right experience.”

Screen size and resolution appear to be the culprits. The Android Developers website states that from Android 1.6 and up, the OS supports three generalized size (large, normal and small) and three generalized densities (high [hdpi], medium [mdpi] and low [ldpi]), with an upper resolution limit of 480×854 on screens measuring from 3.5 inches to 4.0 inches diagonal. Google has hinted that future Android versions beginning with 3.0 (a.k.a. ‘Gingerbread’) will support the larger tablet form factor.

As for BlackBerry App World, RIM confirmed the 10,000 application benchmark via its Twitter account. RIM recently stated that more than 30 million BlackBerry smartphone users across 65 countries have downloaded BlackBerry App World since it first opened in spring 2009, with consumers averaging more than a million app downloads each day. RIM rolled out a revamped BlackBerry App World in late July–the store now supports credit card payments on top of PayPal, with a handful of carrier partners offering operator billing options as well. BlackBerry App World also boasts new tabbed sections for various application lists: Users can horizontally swipe or scroll to view the Top 25 Free Apps, Top 25 Paid Apps and Top 25 Themes, along with checklists spotlighting the Newest Apps and Recently Updated Apps.

For more on Android Market:
- read this TechRadar article

Related articles:
Distimo: 60 percent of Android apps are free
Android Market
adds licensing service to combat app piracy
Google opens up Android development, expands app billing options
Google looks to emerging markets to boost Android   

Tags: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Free apps dominate Android Market, but at what cost?

Jason Akeny

Android keeps growing, and so does the number of free applications in Google’s Android Market–free apps now make up 60 percent of the digital storefront’s inventory, up 3 percent since May, according to new data issued by app store analytics firm Distimo. By comparison, Microsoft’s Windows Marketplace for Mobile boasts the smallest percentage of free apps at 22 percent, with free apps making up 26 percent of both Apple’s (NASDAQ:AAPL) App Store for the iPad and Research In Motion’s (NASDAQ:RIMM) BlackBerry App World. Distimo offers multiple theories to explain the scarcity of premium Android apps: For one, developers in only nine countries are presently able to distribute paid applications via Android Market–moreover, paid apps are available in only 14 of the 46 countries that Android Market serves. Distimo adds that consumers must register for a Google Checkout account in order to download paid applications, except in locations where operator billing is available.

The challenges inherent in distributing and selling premium applications via Android Market have no doubt slowed developer interest in the platform. But Bloomberg reports that with consumer interest in Android exploding, an increasing number of developers are writing apps for the OS anyway, confident a major payday looms in the future. PopCap Games, creator of titles like Bejeweled and Plants vs. Zombies, plans to introduce its first Android games later this year: “Even though we are not making any money on Android right now, we have pretty high hopes for it,” PopCap’s director of mobile business development Andrew Stein said. “There’s really no reason why users shouldn’t consume and buy content to the same extent on an Android phone as they are on an iPhone.”

Even so, developer frustration with Android is at an all-time high–in recent weeks, a series of prominent developers have publicly vented their problems with the platform. The most scathing comments originated via mobile software engineer Joe Hewitt, the developer responsible for social networking giant Facebook’s wildly popular iPhone application: “Android tools are horrendous, OS is hideous, but the absence of big brother telling me what to do gives it a slight edge,” he recently wrote on Twitter. Hewitt’s previous tweets include comments like “The more I work with Android the more it reminds me of Windows… as in, it’s really flexible, agnostic, and developer-friendly, but also really sloppily designed,” “Android fragmentation will hopefully stabilize within 2 years, and if not, at least people upgrade phones much more often than computers” and “Once a day or so it hits me that I am writing Java, and I cry a little.”

eBay Mobile product manager David Beach is a bit more complimentary, writing on his blog that “Creating an open source mobile platform was one of the smarter things Google has done. It’s too bad that they haven’t done that great of a job doing it. Android has succeeded despite Google. In fact it’s safe to say that Android is successful for one primary reason. The iPhone is only available on AT&T. If the iPhone was on Verizon a year ago, Android would be nowhere near as popular. But since this has yet to happen, Android has become a huge market that isn’t going away.” Beach concedes that it’s time for iPhone developers to begin writing for Android as well, but adds a number of caveats, among them the absence of human interface guidelines, a surplus of OS versions and handset models and Android Market’s clunky consumer experience. “There are some good things,” Beach adds. “Don’t get me wrong. In fact over the past nine months, I’ve sort of fallen in love with Android and all its quirks. It’s a tough love, but love nonetheless.”

Last but not least, Digital Chocolate founder Trip Hawkins pinpoints arguably the most significant reason why Android Market is so short on premium applications: Google’s commitment to allowing consumers to return a downloaded app within 24 hours for a full refund. Calling the refund policy “senseless and lazy,” Hawkins writes “When so many other things on the app store are already free and everything else is free for 24 hours, why would anyone pay for a game? Google defends this policy because they don’t want to police the store. I could understand this if Google were a new startup with a small staff incurring startup losses. But we are talking about Google! If Apple and others can pay attention to what is in their app store, surely Google can also do so. Google has ignored this problem and may remain in denial until 2011, when the widening deficit in their app quality compared with Facebook and Apple should finally motivate them to fix the problem.” It’s your move, Google. -Jason

Tags: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -