10 awesome jQuery snippets

Preloading images

Preloading images is useful: Instead of loading an image when the user request it, we preload them in the background so they are ready to be displayed. Doing so in jQuery is very simple, as shown below:

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }

jQuery.preLoadImages("image1.gif", "/path/to/image2.png");

→ Source: http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript

target=”blank” links

The following snippet will open all links with the rel="external" attribute in a new tab/window. The code can be easily customized to only open links with a specific class.

$('a[@rel$='external']').click(function(){
     this.target = "_blank";
});

/*
   Usage:
   <a href="http://www.catswhocode.com" rel="external">catswhocode.com</a>
*/

→ Source: http://snipplr.com/view/315/-jquery–target-blank-links/

Add a class to the <body> tag if JavaScript is enabled

This snippet is just a line of code, but it is one of the easiest way to detect if JavaScript is enabled on the client browser. If yes, a hasJS class will be added to the <body> tag.

$('body').addClass('hasJS');

→ Source: http://eisabainyo.net/weblog/2010/09/01/10-useful-jquery-snippets/

Smooth scrolling to an anchor

jQuery is known for its ability to let developers easily create stunning visual effects. A simple, but nice effect is smooth sliding to an anchor. The following snippet will create a smooth sliding effect when a link with the topLink class is clicked.

$(document).ready(function() {
	$("a.topLink").click(function() {
		$("html, body").animate({
			scrollTop: $($(this).attr("href")).offset().top + "px"
		}, {
			duration: 500,
			easing: "swing"
		});
		return false;
	});
});

→ Source: http://snipplr.com/view.php?codeview&id=26739

Fade in/out on hover

Another very cool effect – which is very popular among clients – is indeed the fade in/fade out on mouseover. The code below set opacity to 100% on hover, and to 60% on mouseout.

$(document).ready(function(){
    $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads

    $(".thumbs img").hover(function(){
        $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
    },function(){
        $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout
    });
});

→ Source: http://snipplr.com/view/18606/

Equal column height

When building a column based website, you often want that all columns have the same height, as displayed in a good old table. This snippet calculate the height of the higher column and automatically adjust all other columns to this height.

var max_height = 0;
$("div.col").each(function(){
    if ($(this).height() > max_height) { max_height = $(this).height(); }
});
$("div.col").height(max_height);

→ Source: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/

Enable HTML5 markup on older browsers

HTML5 is definitely the future of client-side web development. Unfortunely, some old browsers do not even recognize new tags such as header or section. This code will force old browsers to recognize the new tags introduced by HTML5.

(function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])}})()

A better solution is to link the .js file to the <head> part of your HTML page:

<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

→ Source: http://remysharp.com/2009/01/07/html5-enabling-script/

Test if the browser supports a specific CSS3 property

Here is a simple jQuery function to check if the client browser supports a specific CSS3 property. In this example, border-radius is the property we want to check, but of course this can be modified easily.

Note that when passing the property, you have to omit the dash to prevent syntax error. So instead of border-radius, you have to pass “borderRadius” or “BorderRadius”.

var supports = (function() {
   var div = document.createElement('div'),
      vendors = 'Khtml Ms O Moz Webkit'.split(' '),
      len = vendors.length;

   return function(prop) {
      if ( prop in div.style ) return true;

      prop = prop.replace(/^[a-z]/, function(val) {
         return val.toUpperCase();
      });

      while(len--) {
         if ( vendors[len] + prop in div.style ) {
            // browser supports box-shadow. Do what you need.
            // Or use a bang (!) to test if the browser doesn't.
            return true;
         }
      }
      return false;
   };
})();

if ( supports('textShadow') ) {
   document.documentElement.className += ' textShadow';

→ Source: http://snipplr.com/view/44079

Get url parameters

Getting url parameters is pretty easy using jQuery. The following snippet will do the job!

$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (!results) { return 0; }
	return results[1] || 0;
}

→ Source: http://snipplr.com/view/26662

Disable the “Enter” key in forms

By default, a form can be submitted by pressing the “Enter” key. Thought, on some form, this keyboard shortcut can cause problems. Here is how you can prevent unwanted form submission by disabling the “Enter” key with jQuery.

$("#form").keypress(function(e) {
  if (e.which == 13) {
    return false;
  }
});

→ Source: http://snipplr.com/view/10943/disable-enter-via-jquery/

WordPress hook: Automatically remove p tags on images

Simply paste the following code on your theme functions.php file, save it, and the <p> tags are gone.

function filter_ptags_on_images($content){
    return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}

add_filter('the_content', 'filter_ptags_on_images');

Thanks to James for the great hack!

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

WordPress hook: Automatically remove p tags on images

How to automatically email contributors when their posts are published

Nothing complicated with this recipe. Copy the code below and paste it on your functions.php file. Then save the file, and you’re done!

function wpr_authorNotification($post_id) {
   global $wpdb;
   $post = get_post($post_id);
   $author = get_userdata($post->post_author);

   $message = "
      Hi ".$author->display_name.",
      Your post, ".$post->post_title." has just been published. Well done!
   ";
   wp_mail($author->user_email, "Your article is online", $message);
}
add_action('publish_post', 'authorNotification');

Thanks to Daniel Pataki for the great piece of code!

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

How to automatically email contributors when their posts are published

How to add your own meta copyright to your WordPress blog

Simply paste the following piece of code on your functions.php. Don’t forget to modify line 5 according to your needs.

add_action("wp_head", "my_copyright_meta");

function my_copyright_meta() {
   if(is_singular()){
      echo "<meta name="copyright" content="© Me, 2011">";
   }
}

Once you saved the code, you’ll see a line like this one on the head section of your html documents:

<meta name="copyright" content="© Me, 2011">

Thanks to Daniel Pataki for the cool tip!

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

How to add your own meta copyright to your WordPress blog

10+ .htaccess snippets to optimize your website

All of the snippets below have to be pasted into your .htaccess file, which is located on the root of your Apache server.
Waring: Always make sure you have a working backup before editing your .htaccess file!

Force trailing slash

Many clients of mine asked me for always having a trailing slash at the end of their urls. Looks like it’s great for SEO. The following snippet will alwyas add a trailing slash to your site urls.

<IfModule mod_rewrite.c>
 RewriteCond %{REQUEST_URI} /+[^\.]+$
 RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</IfModule>

Source: http://perishablepress.com/code-snippets/

Prevent hotlinking

Hotlinking (the act of using images from another site than yours) is unfortunely a common practice which can waste lots of your precious bandwidth. This useful snippets will redirect all hotlinked images to a specific image, defined on line 6.

RewriteEngine On
#Replace ?mysite\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your "don't hotlink" image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

Source: http://www.wprecipes.com/how-to-protect-your…

Redirect mobile devices

If your site is not using responsive web design yet, it could be very useful to be able to redirect mobile device to a mobile-specific version of your website.

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_ACCEPT} "text/vnd.wap.wml|application/vnd.wap.xhtml+xml" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT}  "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC]
#------------- The line below excludes the iPad
RewriteCond %{HTTP_USER_AGENT} !^.*iPad.*$
#-------------
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC] #*SEE NOTE BELOW
RewriteRule ^(.*)$ /m/ [L,R=302]

Source: http://snipplr.com/view.php?codeview&id=55114

Force download of a specific filetype

For some reasons you may need to force download of specific files, such as MP3s or XLS. This code snippets will prevent your visitor’s browser to read the file and force downloading instead.

<Files *.xls>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>
<Files *.eps>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>

Source: http://snipplr.com/view.php?codeview&id=54752

Cross Domain Font embedding for Firefox

When embedding a font, Firefox do not allow you to embed from an external website. Using the .htaccess snippet below, you can bypass this limitation.

<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "http://yourdomain.com"
</IfModule>
</FilesMatch>

Source: http://snipplr.com/view/53703

Speed up your site with .htaccess caching

This is probably the most useful snippet of this whole list. By using some simple .htaccess file cahing, you can dramatically increase your website speed. A snippet you should always have on your toolbox!

# 1 YEAR
<FilesMatch "\.(ico|pdf|flv)$">
Header set Cache-Control "max-age=29030400, public"
</FilesMatch>
# 1 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
# 2 DAYS
<FilesMatch "\.(xml|txt|css|js)$">
Header set Cache-Control "max-age=172800, proxy-revalidate"
</FilesMatch>
# 1 MIN
<FilesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=60, private, proxy-revalidate"
</FilesMatch>

Source: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html

Stop spam on your WordPress blog

Sick of spammers on your WordPress blog? Of course, Akismet helps a lot, but your .htaccess file can also help: Today’s recipe is a snippet that prevent spam bots to directly access your wp-comments-post.php file, which is used to post comments on your blog.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
</IfModule>

Source: http://www.wprecipes.com/reduce-spam-on-your-wordpress-blog-by-using-htaccess

Redirect different feeds to a single format

Years ago, differents feed formats, such as RSS, Atom or Rdf were used. Nowadays, it seems that RSS is definitely the most used. This snippets allows you to redirect all feeds formats to a single feed. This snippet can be used “as it” on WordPress blogs.

<IfModule mod_alias.c>
 RedirectMatch 301 /feed/(atom|rdf|rss|rss2)/?$ http://example.com/feed/
 RedirectMatch 301 /comments/feed/(atom|rdf|rss|rss2)/?$ http://example.com/comments/feed/
</IfModule>

Source: http://www.wprecipes.com/redirect-feeds-to-a-single-format

Configure your website for HTML5 videos

HTML5 is bringing lots of new exiting options in the world of web development. Among other cool features, being able to play videos without using Flash is really cool. Though, you have to configure your server properly to work with the latest HTML5 video standards. This snippet will definitely help.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
AddType video/ogg .ogv
AddType video/ogg .ogg
AddType video/mp4 .mp4
AddType video/webm .webm
AddType application/x-shockwave-flash swf

Source: http://snipplr.com/view.php?codeview&id=53437

Log PHP errors

Instead of displaying PHP errors to your site (and to possible hackers…) this code snippet will log it into a .log file while hiding errors to visitors.

# display no errs to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /location/to/php_error.log

Source: http://css-tricks.com/snippets/htaccess/php-error-logging/

Run PHP inside JavaScript files

When coding in JavaScript, it can very useful to be able to use PHP inside the .js files, for example for retrieving data from your database. Here is a snippet to allow the use of PHP inside .js files.

AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js

<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>

Source: http://www.kavoir.com/2010/07/how-to-execute-run-php-code-inside-javascript-files.html

How to create a login form shortcode for your WordPress blog

Paste the code below into your functions.php file:

function devpress_login_form_shortcode() {
	if ( is_user_logged_in() )
		return '';

	return wp_login_form( array( 'echo' => false ) );
}

function devpress_add_shortcodes() {
	add_shortcode( 'devpress-login-form', 'devpress_login_form_shortcode' );
}

add_action( 'init', 'devpress_add_shortcodes' );

Once done, you can now use the shortcode as shown in the following example. Simply paste it on the post editor, where you want the login form to be displayed.

[devpress-login-form]

Thanks to DevPress for the cool tip!

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

How to create a login form shortcode for your WordPress blog

Awesome tutorials to master responsive web design

Create an adaptable website layout with CSS3 media queries


With the rise of both very large screens and mobile devices, web developers have to be able to create websites that display correctly and look good whatever the device is. Sure, you can use good old techniques like fluid layouts, but I’ve got something better to show you today. This tutorial will teach you how you can create an adaptable website layout using CSS3.
→ Read tutorial: Create an adaptable website layout with CSS3 media queries

Fluid images


This tutorial will shown you how to make your image scales down when the browser is resized or when your website is viewed through a smaller screen.
→ Read tutorial: Fluid images

Elastic videos


Nowadays, videos are widely used on the web. This useful tutorial written by Nick La (I’ve always be a fan of his work!) will show you how to make your videos scales down according to the window size.
→ Read tutorial: CSS3: Elastic videos

Optimizing your emails for mobile devices


As mobile devices are more and more used, more people are receiving their emails on their phones instead of their computer. For this reason, it is important that newsletter emails can be easily read on a small screen. This tutorial is going to show you how to create html emails than can adapt to mobile devices. A must read for everyone sending newsletters!
→ Read tutorial: Optimizing your emails for mobile devices with the @media query

Images that match text height


This tutorial descibres a very clever way to fill up the entire available space with images. Images are scaled, they are spaced more or less according to the text height.
→ Read tutorial: CSS effect: space images out to match text height

Hiding and revealing portions of images


Here is another great tutorial from zomigi.com. This useful article describes how to be able to reveal or hide portions of images depending of the screen size.
→ Read tutorial: Hiding and revealing portions of images

Responsive Data Tables


Wanna be able to create awesome tables that fits the display size? Chris Coyier from css-tricks.com have a very good post about the topic.
→ Read tutorial: Responsive Data Tables

Context-Aware Image Sizing


The technique described on this article is pretty interesting and consist in loading an image depending of the screen size. For example, if someone is viewing your website on an iPhone, he’ll see a low-resolution image, because it is useless to display 2000px wide images on small devices. On the other hand, people viewing your site on a computer will get a hi-resolution image.
→ Read tutorial: Responsive Images: Experimenting with Context-Aware Image Sizing

Elastic text with Fittext.js


Well, this is more a tool than a tutorial, but Fittext is so useful than it totally deserve its place on this article. FitText is a small JavaScript tool that allows the automatic resizing of a text regarding the size of its parent element. For a demo, just have a look to the website and resize your browser: The text will fit.
→ Read tutorial: Fittext

How to change WordPress default FROM email address

Simply paste the following snippet into your functions.php file. Don’t forget to put the desired email adress on line 5 and desired name on line 8.

add_filter('wp_mail_from', 'new_mail_from');
add_filter('wp_mail_from_name', 'new_mail_from_name');

function new_mail_from($old) {
 return '[email protected]';
}
function new_mail_from_name($old) {
 return 'Your Blog Name';
}

Credits: Rainy Day Media.

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

How to change WordPress default FROM email address

7 new techniques every web developer should know

CSS3 media queries

With the rise of mobile devices, and on the other hand, of very wide displays, creating a website that looks great in both big and small devices is definitely a challenge for web designers and developers. Happily, the CSS3 specification have a new feature which allow web developers to define styles for a specific display size only.

For example, the code below show how to apply a specific style only if the client display is smaller than 767px.

@media screen and (max-width:767px){
	#container{
		width:320px;
	} 

	header h1#logo a{
		width:320px;
		height:44px;
		background:url(image-small.jpg) no-repeat 0 0;
	}                           

}

More info: Create an adaptable website layout with CSS3 media queries

Font resizing with REMs

CSS3 introduces a few new units, including the rem unit, which stands for “root em”. If this hasn’t put you to sleep yet, then let’s look at how rem works.

The em unit is relative to the font-size of the parent, which causes the compounding issue. The rem unit is relative to the root—or the html—element. That means that we can define a single font size on the html element and define all rem units to be a percentage of that.

html { font-size: 62.5%; }
body { font-size: 1.4rem; } /* =14px */
h1   { font-size: 2.4rem; } /* =24px */

More info: Font resizing with REMs

Cache pages for offline usage

HTML5 introduces a great feature, offline caching. Basically, this feature allows you to tell the client browser to cache some pages so your visitor will be able to view it again, even if he’s not connected to the Internet.

Caching pages is pretty easy. The first thing to do is to add the following to your site .htaccess file:

AddType text/cache-manifest .manifest

Once done, you can create a file named, for example, offline.manifest, with the following directives:

CACHE MANIFEST

CACHE
index.html
style.css
image.jpg

And finally, link your .manifest file to your html document:

<html manifest="/offline.manifest">

That’s all, and your page will now be cached if the client browser supports this technology.
More info: How to create offline HTML5 web apps in 5 easy steps

Server-side JavaScript

Since the mid-90′s, JavaScript has been a very popular client-side language for web developers. But nowadays, JavaScript is becoming more and more used on the server side. Why? Because now we have powerful server-side JavaScript environments such as Jaxer, Node.js and Narwhal.

The code belows demonstrate how to create a simple Hello World using Node.js.

var sys = require("sys");
sys.puts("Hello World!");

More info: Learning Server-Side JavaScript with Node.js

HTML5 drag & drop

Thanks to new technologies such as HTML5, the web is becoming more and more user-friendly. Now, it is possible to easily implement drag and drop on your web pages. This is very useful, for example for a shopping basket.

In order to make an element draggable, you simply have to add it the draggable="true" attribute, as shown in the example below:

<div id="columns">
  <div class="column" draggable="true"><header>A</header></div>
  <div class="column" draggable="true"><header>B</header></div>
  <div class="column" draggable="true"><header>C</header></div>
</div>

Of course, after you made an element draggable, you have to use some JavaScript to control what it should do. I’m not going to explain how to do it (This may be a full article!) so you definitely have a look there if you’re interested in the topic.

Quick tip: If you want to prevent the text contents of draggable elements from being selectable, simply apply the following CSS rules:

[draggable] {
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}

More info: Cross Browser HTML5 Drag and Drop

Forms, the HTML5 way

The HTML5 specification introduces lots of new features regarding one of the most important element of a website: forms. For example, it is now possible to add date pickers, numeric spinners, as well as validating emails using regular expressions patterns.

The following code is pretty self-explanatory and shows most of the new forms-specific features introduced in the HTML5 specification.

<form>
	<label for="range-slider">Slider</label>
	<input type="range" name="range-slider" id="range-slider" class="slider" min="0" max="20" step="1" value="0">

	<label for="numeric-spinner">Numeric spinner</label>
	<input type="number" name="numeric-spinner" id="numeric-spinner" value="2">

	<label for="date-picker">Date picker</label>
	<input type="date" name="date-picker" id="date-picker" value="2010-10-06">

	<label for="color-picker">Color picker</label>
	<input type="color" name="color-picker" id="color-picker" value="ff0000">

	<label for="text-field">Text field with placeholder</label>
	<input type="text" name="text-field" id="text-field" placeholder="Insert your text here">

	<label for="url-field">Url field</label>
	<input type="url" id="url-field" name="url-field" placeholder="http://net.tutsplus.com/" required>

	<label for="email-field">Email field</label>
	<input type="email" id="email-field" name="email-field" placeholder="[email protected]" required>

	<button type="submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
	<span class="ui-button-text">Submit form</span>
	</button>
</form>

More info: How to Build Cross-Browser HTML5 Forms

CSS animations

Most modern browsers are now supporting CSS animations. Yes, CSS are now allowing you to create some simple animations, without the help of a client-side programming language such as JavaScript.

The following example shows how to make a background color change. As you can see, we have (for now) to use some proprietary properties such as -moz-keyframes.

#logo {
	margin: 15px 15px 0 15px;
	background: red;
	float: left;

	/* Firefox 4+ */
	-moz-animation-name: colour-change;
	-moz-animation-timing-function: linear;
	-moz-animation-iteration-count: infinite;
	-moz-animation-duration: 30s;

	/* Webkit */
	-webkit-animation-name: colour-change;
	-webkit-animation-timing-function: linear;
	-webkit-animation-iteration-count: infinite;
	-webkit-animation-duration: 30s;
}

@-moz-keyframes colour-change {
    0% {
		background: red;
    }
	33% {
		background: green;
    }
    66% {
    	background: blue;
    }
}

@-webkit-keyframes colour-change {
    0% {
		background: red;
    }
	33% {
		background: green;
    }
    66% {
    	background: blue;
    }
}

More info: Enhance Your Sites with CSS3 Animations

How to retrieve a remote page using WordPress

Just use the wp_remote_get() function (Or wp_remote_post() is you prefer using the POST method) to retrieve the desired url. The example below shows how to retrieve an url and display its content as well as the file info.

This code can be used anywhere on your template files.

$response = wp_remote_get( 'http://foo.com/file.txt' );
if( is_wp_error( $response ) ) {
   echo 'Something went wrong!';
} else {
   echo 'Response:<pre>';
   print_r( $response );
   echo '</pre>';
}

Credits: WordPress Codex.

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

How to retrieve a remote page using WordPress

Automatically prefetch next pages on your WordPress blog

First, if you don’t know what prefetching is, you should have a look at this post first.

Simply paste the code below in your header.php file (Within the <head> and </head> tags)

<?php if (is_archive() && ($paged > 1) && ($paged < $wp_query->max_num_pages)) { ?>
<link rel="prefetch" href="<?php echo get_next_posts_page_link(); ?>">
<link rel="prerender" href="<?php echo get_next_posts_page_link(); ?>">
<?php } ?>

Thanks to Bernd for the cool snippet!

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

Automatically prefetch next pages on your WordPress blog

Mastering HTML5 Prefetching

What is prefetching, and why it is useful

According to whatwg.org, rel=prefetch "indicates that preemptively fetching and caching the specified resource is likely to be beneficial, as it is highly likely that the user will require this resource." Search engines sometimes add <link rel=prefetch href="URL of top search result"> to the search results page if they feel that the top result is wildly more popular than any other.
For example: using Firefox, search Google for CNN; view source; search for the keyword "prefetch".

As loading time is a very important factor of a website quality, prefetching can definitely improve the user experience by loading pages before the user actually requested them. Of course, you have to be careful (Don’t prefetch your entire website!) but prefetching is definitely a feature that will make the web a better place.

Prefetching pages with HTML5

Prefetching pages is super easy to implement. The only thing you have to do is to place the following code with the <head> and </head> tags of your page. The href attribute have to contain the url of the page to prefetch.

<link rel="prefetch" href="http://www.example.com/">

It is also possible to prefetch only an image:

<link rel="prefetch" href="http://www.catswhocode.com/wp-content/uploads/my_image.png">

Browser support

As prefetching (Or prerendering as Google Chrome name that feature) is a part of HTML5, it is currently not supported in all browsers:

  • Mozilla Firefox: Supported
  • Google Chrome: Supported since version 13 (Use an alternate syntax)
  • Safari: Currently not supported
  • Internet Explorer: Currently not supported

So, should you use it now? In my humble opinion, the answer is a definitive yes: Using prefetching now is possible in both Firefox and Chrome, and other browsers will probably implement it very soon.

Also, if you use prefetching on your website and the visitor browser do not support prefetching, nothing will happen. For what I’ve seen during some personal tests, it is safe to use prefetching as browsers will either implement it, or completely ignore it.

Another thing to note is that Google Chrome do not use the prefetch attribute and use prerender instead. This means that you have to implement both prefetch and prerender, as shown in the example below:

<link rel="prefetch" href="http://www.example.com/"> <!-- Firefox -->
<link rel="prerender" href="http://www.example.com/"> <!-- Chrome -->

Prefetching pages on your WordPress blog

As I know most of my readers are WordPress users, I thought about a WordPress-specific example of HTML5 prefetching. A blog is typically the kind of website where prefetching can be very useful: On many situations, it is possible to “guess” which page the visitor will want to read next.

For example, if a visitor is currently having a look to the second page of your archives, it is highly possible that he’ll read the third page next. The following code snippet (Courtesy of Bernd) is ready to use: Just paste it into the header.php file of your theme in order to prefetch next archive pages.

<?php if (is_archive() && ($paged > 1) && ($paged < $wp_query->max_num_pages)) { ?>
<link rel="prefetch" href="<?php echo get_next_posts_page_link(); ?>">
<link rel="prerender" href="<?php echo get_next_posts_page_link(); ?>">
<?php } ?>

Of course, the version above can be enhanced according to your site own needs. According to my analytics, most people comes to my site on an article page like this one, and then, have a look to the home page. So, it can be great to add a new condition to the code above and prefetch the home page when the visitor is reading an article.

<?php if (is_archive() && ($paged > 1) && ($paged < $wp_query->max_num_pages)) { ?>
<link rel="prefetch" href="<?php echo get_next_posts_page_link(); ?>">
<link rel="prerender" href="<?php echo get_next_posts_page_link(); ?>">
<?php } elseif (is_singular()) { ?>
<link rel="prefetch" href="<?php bloginfo('home'); ?>">
<link rel="prerender" href="<?php bloginfo('home'); ?>">
<?php } ?>

Prefetching using jQuery

Now that we saw what prefetching can do for you, what about using jQuery to automatically prefetch each link with the prefetch class? That’s exactly what the snippet below do. Simply paste it to your website, and then add a prefetch class to each link you’d like to prefetch.

// create an object named "app" which we can define methods on
var app = {
    // returns an array of each url to prefetch
    prefetchLinks: function(){
        // returns an array of each a.prefetch link's href
        var hrefs = $("a.prefetch").map(function(index, domElement){
            return $(this).attr("href");
        });
        // returns the array of hrefs without duplicates
        return $.unique(hrefs);
    },

    // adds a link tag to the document head for each of prefetchLinks()
    addPrefetchTags: function(){
        // for each prefetchLinks() ...
        this.prefetchLinks().each(function(index,Element){
            // create a link element...
            $("<link />", {
                // with rel=prefetch and href=Element...
                rel: "prefetch", href: Element
                // and append it to the end of the document head
            }).appendTo("head");
        });
    },
}
// when the document is ready...
jQuery(function(){
  // call the method we defined above.
    app.addPrefetchTags();
}

Thanks to Gavin Morrice for this great snippet!

How to automatically obfuscate email adresses on your WordPress blog

This tip is pretty easy to use. Just use the antispambot() function anywhere in your theme templates:

<?php antispambot('[email protected]',1 ) ?>

But what if you need to type email adresses in WP editor? No problem, I have a shortcode for that! Just have a look on CatsWhoCode.com.

Credits: WordPress Codex

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

How to automatically obfuscate email adresses on your WordPress blog

How to display a thumbnail from a Youtube using a shortcode

First, you need to create the shortcode. To do so, copy the code below and paste it into your functions.php file.

/*
    Shortcode to display youtube thumbnail on your wordpress blog.
    Usage:
    [youtube_thumb id="VIDEO_ID" img="0" align="left"]
    VIDEO_ID= Youtube video id
    img=0,1,2 or 3
    align= left,right,center
*/
function wp_youtube_video_thumbnail($atts) {
     extract(shortcode_atts(array(
          'id' => '',
          'img' => '0',
          'align'=>'left'
     ), $atts));
    $align_class='align'.$align;
    return '<img src="<a href="http://img.youtube.com/vi/'.$id.'/'.$img.'.jpg&quot" rel="nofollow">http://img.youtube.com/vi/'.$id.'/'.$img.'.jpg&quot</a>; alt="" class="'.$align_class.'" />';
}
add_shortcode('youtube_thumb', 'wp_youtube_video_thumbnail');

Once done, you can use the shortcode. It accept 3 parameters: The video ID, the image size (0 for 480*360px, 1 for 120*90) and the image alignment.

[youtube_thumb id="rNWeBVBqo2c" img="0" align="center"]

Thanks to Gunay for the great code!

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

How to display a thumbnail from a Youtube using a shortcode

10 super useful WordPress shortcodes

Display a snapshot of any website

Want to be able to take a snapshot of any website, and display it on your blog? This cool shortcode allows you to do so. Just paste the following code into your functions.php file:

function wpr_snap($atts, $content = null) {
        extract(shortcode_atts(array(
			"snap" => 'http://s.wordpress.com/mshots/v1/',
			"url" => 'http://www.catswhocode.com',
			"alt" => 'My image',
			"w" => '400', // width
			"h" => '300' // height
        ), $atts));

	$img = '<img src="' . $snap . '' . urlencode($url) . '?w=' . $w . '&h=' . $h . '" alt="' . $alt . '"/>';
        return $img;
}

add_shortcode("snap", "wpr_snap");

Once done, you can use the snap shortcode, as shown in the following example. It will display a CatsWhoCode.com snapshot on your own blog!

[snap url="http://www.catswhocode.com" alt="My description" w="400" h="300"]

Source: http://www.geekeries.fr/snippet/creer-automatiquement-miniatures-sites-wordpress/

Add a Paypal donation link easily

Many bloggers are asking support from their readers in the form of a Paypal donation. The following code creates a shortcode which will display a Paypal “donate” button on your site. Just paste the code below into your functions.php file:

function cwc_donate_shortcode( $atts ) {
    extract(shortcode_atts(array(
        'text' => 'Make a donation',
        'account' => 'REPLACE ME',
        'for' => '',
    ), $atts));

    global $post;

    if (!$for) $for = str_replace(" ","+",$post->post_title);

    return '<a class="donateLink" href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation+for+'.$for.'">'.$text.'</a>';

}
add_shortcode('donate', 'cwc_donate_shortcode');

Source: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress/

Obfuscate email addresses

As most of you know, spam bots are constantly scanning the internet in order to find emails to spam. Of course, you don’t want to receive spam, but what if you need to display your email (or someone else) on your blog? This code will create a shortcode which will obfuscate email adresses. As usual, let’s start by creating the shortcode: paste the code into your functions.php file.

function cwc_mail_shortcode( $atts , $content=null ) {
    for ($i = 0; $i < strlen($content); $i++) $encodedmail .= "&#" . ord($content[$i]) . ';';
    return '<a href="mailto:'.$encodedmail.'">'.$encodedmail.'</a>';
}
add_shortcode('mailto', 'cwc_mail_shortcode');

Then you can use the shortcode, which is pretty easy:

[mailto][email protected][/mailto]

Source: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress/

Create private content

If you want to create some private content that only registered users are able to see, the following shortcode is the solution to your problem. Paste the code below into your functions.php file in order to create the shortcode:

function cwc_member_check_shortcode( $atts, $content = null ) {
	 if ( is_user_logged_in() && !is_null( $content ) && !is_feed() )
		return $content;
	return '';
}

add_shortcode( 'member', 'cwc_member_check_shortcode' );

Then, proceed as shown below to create some member-only content:

[member]This text will be only displayed to registered users.[/member]

Source: http://snipplr.com/view.php?codeview&id=46936

Embed a PDF in an iframe

This is definitely the easiest way to display a PDF file on your website: The PDF is loaded through Google docs and then displayed in an iframe, on your own site.
To use this shortcode, first paste the code below into your functions.php file:

function cwc_viewpdf($attr, $url) {
    return '<iframe src="http://docs.google.com/viewer?url=' . $url . '&embedded=true" style="width:' .$attr['width']. '; height:' .$attr['height']. ';" frameborder="0">Your browser should support iFrame to view this PDF document</iframe>';
}
add_shortcode('embedpdf', 'cwc_viewpdf');

Then, use the following syntax to display a PDF. As you can see, it is possible to define width and height, which means that this shortcode will fit great on your blog, nevermind its layout.

[embedpdf width="600px" height="500px"]http://infolab.stanford.edu/pub/papers/google.pdf[/embedpdf]

Source: http://snipplr.com/view.php?codeview&id=35682

“Feed only” content shortcode

This shortcode create some content that will only be displayed on your RSS feed. Quite good to display some RSS-only ads, or an important message for your feed readers. The function have to be pasted in your functions.php. What, you guessed that? ;)

function cwc_feedonly_shortcode( $atts, $content = null) {
	if (!is_feed()) return "";
	return $content;
}
add_shortcode('feedonly', 'cwc_feedonly_shortcode');

Then, you can use the shortcode as shown below:

[feedonly]Dear RSS readers, please visit <a href="http://yourwebsite.com">my website</a> and click on a few ads[/feedonly]

Source: http://kovshenin.com/archives/snippet-a-feed-only-shortcode-for-wordpress/

“Retweet” shortcode using Tweetmeme

Tweeter is definitely a great source of trafic for bloggers. This is why this “Retweet” shortcode can be very useful. Paste the following code in your functions.php file in order to create the shortcode:

function tweetmeme(){
	return '<div class="tweetmeme"><script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script></div>';
}
add_shortcode('tweet', 'tweetmeme');

Once done, you can display the Tweetmeme “retweet” button anywhere on your posts. In WordPress editor, make sure you are in HTML mode and insert the following:

[tweet]

Source: http://www.wprecipes.com/wordpress-tip-create-a-tweetmeme-retweeet-shortcode

Display the last image attached to post

Instead of dealing with image url, a simple shortcode can retrieve and display the last image attached to post. Paste the code below into your functions.php file in order to create the shortcode:

function cwc_postimage($atts, $content = null) {
	extract(shortcode_atts(array(
		"size" => 'thumbnail',
		"float" => 'none'
	), $atts));
	$images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );
	foreach( $images as $imageID => $imagePost )
	$fullimage = wp_get_attachment_image($imageID, $size, false);
	$imagedata = wp_get_attachment_image_src($imageID, $size, false);
	$width = ($imagedata[1]+2);
	$height = ($imagedata[2]+2);
	return '<div class="postimage" style="width: '.$width.'px; height: '.$height.'px; float: '.$float.';">'.$fullimage.'</div>';
}
add_shortcode("postimage", "cwc_postimage");

Once done, you can display the last image by using the shortcode:

[postimage]

Source: http://www.wprecipes.com/wordpress-shortcode-easily-display-the-last-image-attached-to-post

Embed Youtube videos

If you often post videos from Youtube on your blog, this shortcode will make you save a lot of time. Let’s start by creating it by pasting the code below into your functions.php file:

function cwc_youtube($atts) {
	extract(shortcode_atts(array(
		"value" => 'http://',
		"width" => '475',
		"height" => '350',
		"name"=> 'movie',
		"allowFullScreen" => 'true',
		"allowScriptAccess"=>'always',
	), $atts));
	return '<object style="height: '.$height.'px; width: '.$width.'px"><param name="'.$name.'" value="'.$value.'"><param name="allowFullScreen" value="'.$allowFullScreen.'"></param><param name="allowScriptAccess" value="'.$allowScriptAccess.'"></param><embed src="'.$value.'" type="application/x-shockwave-flash" allowfullscreen="'.$allowFullScreen.'" allowScriptAccess="'.$allowScriptAccess.'" width="'.$width.'" height="'.$height.'"></embed></object>';
}
add_shortcode("youtube", "cwc_youtube");

Using the shortcode is pretty easy:

[youtube value="http://www.youtube.com/watch?v=1aBSPn2P9bg"]

Source: http://wpsnipp.com/index.php/functions-php/display-youtube-video-with-embed-shortcode/

Embed a RSS feed

This shortcode allows you to embed any RSS feed on your blog posts. Definitely cool for showcasing other blogs on your site! Just paste the code below into your functions.php file:

include_once(ABSPATH.WPINC.'/rss.php');

function cwc_readRss($atts) {
    extract(shortcode_atts(array(
	"feed" => 'http://',
      "num" => '1',
    ), $atts));

    return wp_rss($feed, $num);
}

add_shortcode('rss', 'cwc_readRss');

Then, you can use the shortcode as shown below:

[rss feed="http://feeds.feedburner.com/catswhocode" num="5"]  

Source: http://coding.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/