Image optimization: Common mistakes and solutions

Image optimization

Using images for things you can do with CSS

There was a time when the CSS specification was pretty basic, and images were needed for backgrounds, shadows, icons, etc. However, with CSS3 being well supported by all major web browsers, you can now make your website faster to load and save on bandwidth by using modern CSS techniques.

Do you need a gradient? You can do it so with pure CSS. Fancy some icons? Don’t use image icons but SVGs or an icon webfont instead.

Using the wrong image format

One super common mistake when it comes to serving images online is to use the wrong format. Let’s sum it up: .jpg, .gif and .png are the three most common formats for images on the Internet. But it doesn’t mean that you should just use whatever format. In fact, each format has its own pros and cons, and using the right format for the right kind of image is something that will definitely make you save bandwidth and load your site faster while still displaying an image in good quality.

Photographs should always be in .jpg format. Logos or charts? .png is the right choice. What about .gif? Only use it for very small images such as a repeated backgrounds, that you can’t do with pure CSS. GIFs are hugely popular when it comes to displaying short, looped videos. But did you know that a 6Mo .gif image has the weight of only a little over 300Kb in .mp4 format?

Another thing to consider are emerging formats. Created by Google, WebP is a modern image format that provides superior lossless and lossy compression (26% smaller in size compared to PNGs) for images on the web. As of now, WebP is natively supported in Chrome and Opera, and there’s no doubt that other major browsers will follow. Microsoft has also created another modern format called JPEG-XR, which is currently supported by Microsoft browsers exclusively.

Using non-optimized images

As a rule of thumb, every image that you display on your website should be optimized. The easiest way to optimize an image is to use Adobe Photoshop’s “Save for Web” feature.

If you’re using WordPress, then you should definitely install the WP Smush plugin: it automatically optimizes all images you upload through the WordPress uploader and reduces them up to 90%, without any compromises on the quality. It also has an option which allows you to batch smush images you have previously uploaded. This plugin is a must-have, definitely! There’s also a premium version of the plugin available, with extra features and increased optimization. I haven’t tested it yet but it looks super interesting.

Using browser resizing on large images

In 2016, it’s mandatory that your website adapts to various devices and resolutions. While making your website responsive is relatively easy, dealing with images is a lot more tricky.

It can be very tempting to use one image, at the maximum resolution needed, and then use browser resizing to scale it down on smaller resolutions. The problem with browser resizing is that you still deliver the same big image, which consequently makes your website long to load on mobile devices and waste bandwidth, as well as your visitor mobile data.

The solution to this problem is to create different thumbnails of the same image and deliver the right image size according to the client resolution. To do so, you can either use an open-source solution such as the well known ImageMagick, or rely on a cloud-based service like Cloudinary.

Not using caching on images

Not caching your image is a mistake that makes your website slower, and costs you extra bandwidth. Images and other static resources should be cached in order to instruct the returning visitor’s browser to reuse a previously fetched resource.

Caching can be implemented easily by pasting the following code into your .htaccess file:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>

If you’re using WordPress, I highly recommend the W3 Total Cache plugin, which offers image caching as well as many different options for a faster website.

Themify Giveaway: Over $300 worth of WordPress themes to win

A word about Themify


Themify creates premium WordPress themes & plugins, that help you make beautiful responsive WordPress sites faster and easier. Together with its powerful, easy-to-use, drag & drop Builder, Themify gives you all the tools you need to design any layout that you can imagine.

Themify offers two different pricing options: the first one lets you pick an individual theme of your choice for $49. You get the chosen theme, one year of support, and another theme of your choice, free of charge.

The second option is more interesting if you’re a developer looking for quality themes for your clients sites: the Themify Club provides you with all current themes, and all future releases for a year, starting at $79. Numerous options are available, such as download of .psd files, lifetime membership, etc.

Themify also offers a few free themes that you might want to check out as well.

How to enter the giveaway

Feeling lucky? Then enter our giveaway and try to grab one of the three prizes below:

First Prize – Master Club

  • Access to all 52+ WordPress themes
  • 10+ plugins
  • 34+ Addons
  • All theme PSD files

Second Prize – Developer Club

  • Access to all 52+ WordPress themes
  • All theme PSD files

Third Prize – Standard Club

  • Access to all 52+ WordPress themes

To take part in the giveaway, just leave a comment on this post to let us know that you’re in. In one week, I will randomly pick three lucky winners who will receive their prize directly from the Themify staff, by email.

Good luck everybody!

Good practices for efficient and maintainable CSS

CSS Optimization

Always create a table of content

As CSS files are becoming bigger and bigger, the easiest way to quickly find what you’re looking for is to create a table of contents and organize your ids and classes.

/* reset  */

/* general */

/* typography */

/* header */

/* footer */

/* sidebar */

/* Home Page */

/* About Page */

/* Media Queries */

Above is an example of a CSS table of contents that you can reuse in your own projects.

Write your CSS the standard way

If you download code from the internet, I’m pretty sure that every once in a while, you stumble upon a very badly written piece of CSS. And the harder a code is to read, the harder it will be to maintain, this is why paying attention to the way you actually write your CSS is important.

There’s two “standard” ways of writing CSS. The first and most widespread is using the “block” style of writing:

#element{
	margin: 0 auto;
	width:80%;
	display: block;
}

And the second is the “line” style:

#element{ margin: 0 auto; width:80%; display: block; }

In my opinion, the “line” style is great to use if you set no more than 3/4 properties. More than that, it can become kind of hard to read.

Use SASS

CSS used to be pretty simple, but as time go by, more and more features and possibilities are added to allow designers and front-end web developers to create awesome websites. But nowadays, a 500 line long stylesheet is not uncommon. Writing them, and especially maintaining them can be tedious.
This is where a preprocessor can help. Sass lets you use features that don’t exist in CSS yet like variables, nesting, mixins, inheritance and more.

Sass offers lots of possibilities which will make your CSS easier to maintain, and faster to write. The best thing is that the whole language is super easy. Below is an example of using variables in Sass:

$font-stack:    Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

Looks appealing, doesn’t it? If you haven’t installed Sass yet, then you probably know what you should do tonight!

Make proper use of ids and classes

In order to avoid redundancy in your stylesheets, it is important to make a proper use of both ids and classes.
Ids are for styling an individual element such as a logo:

#logo{
	width: 250px;
	height:90px;
	display: block;
	float:left;
}

On the other hand, classes are made to define styles that would be applied to various elements:

.box{
	background: #E4F0FC;
	margin: 1em 0px 1.5em;
	padding: 9px 10px 9px 15px;
	color: #555;
	text-shadow: none;
	font-weight: bold;
}

An element can have both an id and one or more class(es) as shown below:

<li id="comment-27299" class="item">

This is useful as you apply a general class to the element and an unique id which allows to set unique properties. For more information about ids and classes, check out this article by CSS master Chris Coyier.

Combine your stylesheets

Everytime you link to a CSS file on a HTML page, the client browser has to do a HTTP request in order to get that file. As each HTTP request takes time, you should always combine all your stylesheets into one and consequently make your website loads a lot faster.

Various tools for combining multiple CSS files are available. I’ve been using the online CSS Compressor with good results so far.

Use an editor

Most people use a very basic editor to create CSS files. While it is doable, using an editor made for CSS can make the whole job easier. There’s lots of different editors available, both free and paid, for all platforms.

My personal pick is Stylizer, a free Windows & Mac editor which provides a real time preview in various browsers and many more super useful features. If you want more choice to pick the perfect CSS editor for your needs, check out this list.

Use free tools to optimize and clean your CSS

There’s a ton of free tools available on the internet that can help you to produce better quality CSS.

Procssor cleans and organizes your CSS the way you want it. It allows you to define indentation, brace style, white space, etc. Perfect for css consistency when multiple people contribute.

Clean CSS is an online tool to beautify, minify, format, or compress CSS files as well as other formats such as JS or HTML.

As you can guess by its name, Unused CSS is a tool that explores all your pages and removes unused CSS and then lets you download the optimized files. A great tool to keep your stylesheets clean and up to date!

Minify or GZip your files

A great way to optimize your website loading speed and save on bandwidth is to minify or compress your CSS files. Minification is the act of removing whitespace, comments, and unnecessary semicolons. A minified CSS style will be about 80% of its original size. CSS files can easily be minified as well as unminified online.

Gzipping reduces response times by reducing the size of the HTTP response. A gzipped stylesheet is generally reduced by about 70%. Gzip can be activated by adding the following code into your server’s .htaccess file:

# BEGIN GZIP
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>
# END GZIP

5 WordPress plugins that will drive traffic to your blog

Revive Old Post


This one is definitely one of my favorite WordPress plugins. Revive Old Post helps you to keep your old posts alive by sharing them and driving more traffic to them from social networks, automatically. There are lots of options that you can set, such as time between two automatic posts, categories or posts to be excluded, etc.

Revive Old Post is also available in a pro version with lots of interesting extra features: include hashtags and images, post to multiple accounts at once, custom schedule, and a lot more.
Free download: Revive Old Post

SEO Smart Links


SEO Smart Links allows you to define a list of words that, if found within your blog posts or pages, will be automatically turned into hyperlinks and displayed on your WordPress theme.

A great way to link back to other posts and maximize your page views, SEO Smart Links can also be used to automatically insert affiliate links on selected words or sentences.
Free download: SEO Smart Links

Monarch


Created by ElegantThemes, Monarch is a premium plugin that displays links to share your content on various social networks such as Facebook, Twitter, Google+ and a ton more. Monarch is very lightweight, fast to load and can be fine tuned to fit all your needs.
Info/Download: Monarch

Yoast SEO


When it comes to driving traffic to your blog, search engines are definitely the best. A post ranking on top of the first page of Google for a given search term can by itself be responsible of 10% to 30% of your whole traffic. WordPress is good for SEO by default, but Yoast SEO can do wonders by helping you to optimize your content for search engine optimization.

An interesting alternative is All-in-One SEO Pack, so be sure to check it as well and see which one works the best for you. Both are free!
Free download: Yoast SEO

Disqus


Disqus in an external commenting system offering many advantages: it helps reducing spam, it can display ads that will get you some money, and it also has strong community features that can drive more traffic to your blog.

While Disqus will not make wonders in terms of traffic, it offers many advantages as discussed before, so why not give it a try and enjoy a little more traffic?

Disqus is free, but if you’re looking for a premium alternative you should have a look at de:comments.
Free download: Disqus

Advanced CSS tricks and techniques

css

Warning: some techniques contained in this article are still considered as experimental. Make sure to check the browser compatibility before you implement them on a production site.

Using SVG for icons

SVG is supported by all modern browsers and scales well for all resolution types, so there’s no reason to continue using .jpg or .gif images for icons. Note the use of the background-size property to scale the background image on the on container size.

.logo {
  display: block;
  text-indent: -9999px;
  width: 100px;
  height: 82px;
  background: url(kiwi.svg);
  background-size: 100px 82px;
}

Source: CSS Tricks

Fixed table layouts

A widely supported but surprisingly little-known property which changes the way the tables are rendered and gives you a sturdier, more predictable layout.

table {
  table-layout: fixed;
}

Source: CSS Tricks

Curve text around a floated image

The shape-outside is a CSS property that allows geometric shapes to be set, in order to define an area for text to flow around.

.shape {
  width: 300px;
  float: left;
  shape-outside: circle(50%);
}

Here’s the result of the .shape class applied to the image:
curved-text-css
Source: WebDesigner Depot

Intrinsic Ratio Boxes

Using 20% for padding makes the height of the box equal to 20% of its width. No matter the width of the viewport, the child div will keep its aspect ratio (100% / 20% = 5:1).

.container {
  height: 0;
  padding-bottom: 20%;
  position: relative;
}

.container div {
  border: 2px dashed #ddd;  
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

Source: AllThingsSmitty

Color fade on hover

A very easy way to make your links (or any other element) look better.

a {
 color: #000;
 -webkit-transition: color 1s ease-in; /*safari and chrome */
 -moz-transition: color 1s ease-in; /* firefox */
 -o-transition: color 1s ease-in; /* opera */
}

a:hover { 
 color: #c00;
}

Source: Matt Lambert

Style broken images

Broken images never look good, but it happens every now and then that one or two images on your site are broken. Using some advanced CSS, it is possible to style broken images and provide custom error messages to your visitors.

img {  
  min-height: 50px;
}

img:before {  
  content: " ";
  display: block;

  position: absolute;
  top: -10px;
  left: 0;
  height: calc(100% + 10px);
  width: 100%;
  background-color: rgb(230, 230, 230);
  border: 2px dotted rgb(200, 200, 200);
  border-radius: 5px;
}

img:after {  
  content: "\f127" " Broken Image of " attr(alt);
  display: block;
  font-size: 16px;
  font-style: normal;
  font-family: FontAwesome;
  color: rgb(100, 100, 100);

  position: absolute;
  top: 5px;
  left: 0;
  width: 100%;
  text-align: center;
}

Look what can be achieved with that technique: way better than browsers’ default, right?
broken-image-css
Source: Bitsofco.de

Empty and not empty attribute selectors

CSS3 makes it easy to apply different styles to an element, depending on whether a data-* attribute is empty or not. Have a look at the HTML code below:

<div data-attr="">
</div>

<div data-attr="value">
</div>

And now, our CSS, with specific styling for any div element with an empty data-attr attribute:

div {
  border: 1px solid gray;
  height: 100px;
  margin: 10px;
  width: 100px;
}

/* Empty attribute selector */
div[data-attr=''] {
  background: red;
}

/* Not empty attribute selector */
div:not([data-attr='']) {
  background: green;
}

Source: Vacheslav Starikov

Comma-Separated Lists

A little snippet to display an unordered list as a comma-separated list. Note the use of :not(:last-child) to ensure that the last list element won’t be followed by a comma.

ul > li:not(:last-child)::after {
  content: ",";
}

Source: AllThingsSmitty

10+ WordPress hacks to enhance your dashboard

Keep logged in on WordPress for a longer period

A very handy code snippet here, which allows you to stay logged in for a longer period of time. Paste the code to functions.php and update, if needed, the amount of seconds to stay logged in on line 3.

add_filter( 'auth_cookie_expiration', 'stay_logged_in_for_1_year' );
function stay_logged_in_for_1_year( $expire ) {
  return 31556926; // 1 year in seconds
}

Source: Labnol

Remove dashboard menus

When building a WordPress blog for a client, it can be a good idea to remove access to some dashboard menus in order to avoid future problems such as the client “accidentally” deleting the custom theme they paid for.
Paste the following code in the functions.php file from your theme directory. The following example will remove all menus named in the $restricted array.

function remove_menus () {
global $menu;
		$restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins'));
		end ($menu);
		while (prev($menu)){
			$value = explode(' ',$menu[key($menu)][0]);
			if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
		}
}
add_action('admin_menu', 'remove_menus');

Source: Hungred

Require a featured image before you can publish posts

If your blog layout is set to display a featured image, it can be useful to prevent post publishing if the post doesn’t have a featured image set.
This code has to be pasted into your functions.php file.

add_action('save_post', 'wpds_check_thumbnail');
add_action('admin_notices', 'wpds_thumbnail_error');

function wpds_check_thumbnail( $post_id ) {
  // change to any custom post type 
  if( get_post_type($post_id) != 'post' )
      return;

  if ( ! has_post_thumbnail( $post_id ) ) {
    // set a transient to show the users an admin message
    set_transient( "has_post_thumbnail", "no" );
    // unhook this function so it doesn't loop infinitely
    remove_action('save_post', 'wpds_check_thumbnail');
    // update the post set it to draft
    wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));

    add_action('save_post', 'wpds_check_thumbnail');
  } else {
    delete_transient( "has_post_thumbnail" );
  }
}

function wpds_thumbnail_error() {
  // check if the transient is set, and display the error message
  if ( get_transient( "has_post_thumbnail" ) == "no" ) {
    echo "<div id='message' class='error'><p><strong>You must add a Featured Image before publishing this. Don't panic, your post is saved.</strong></p></div>";
    delete_transient( "has_post_thumbnail" );
  }
}

Source: WP Snipp

Replace dashboard logo with yours

Just as a client will love to see their own logo on WordPress login page, there’s no doubt that they’ll enjoy viewing it on the dashboard too.
Simply copy the code below and paste it to your functions.php file.

add_action('admin_head', 'my_custom_logo');

function my_custom_logo() {
   echo '<style type="text/css">
         #header-logo { background-image: url('.get_bloginfo('template_directory').'/images/custom-logo.gif) !important; }</style>';
}

Source: Smashing Magazine

Remove dashboard widgets

Introduced in WordPress 2.7, dashboard widgets can be pretty useful. For example, some can display your Google Analytics stats. Though, sometimes you don’t need it, or at least don’t need some of them.
The code below will allow you to remove WordPress’ dashboard widgets once you paste it in your functions.php file.

function example_remove_dashboard_widgets() {
	// Globalize the metaboxes array, this holds all the widgets for wp-admin
 	global $wp_meta_boxes;

	// Remove the incomming links widget
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);	

	// Remove right now
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
	unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
	unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
}

// Hook into the 'wp_dashboard_setup' action to register our function
add_action('wp_dashboard_setup', 'example_remove_dashboard_widgets' );

Source: Hankis

Define your own login logo

Although it doesn’t have any importance for the blog performance or usability, most clients will be very happy to see their own logo on the dashboard login page, instead of the classic WordPress logo.
The Custom admin branding plugin can do that for you, as well as the following hack that you just have to paste in your functions.php file.

function my_custom_login_logo() {
    echo '<style type="text/css">
        h1 a { background-image:url('.get_bloginfo('template_directory').'/images/custom-login-logo.gif) !important; }
    </style>';
}

add_action('login_head', 'my_custom_login_logo');

Source: WPRecipes

Add custom widgets to WordPress dashboard

With the previous example, I showed you how easy it is to remove unwanted dashboard widgets. The good news is that creating your own widgets isn’t hard either.
The well-commented code below should be self-explanatory. Just insert it in your functions.php, as usual.

function example_dashboard_widget_function() {
	// Display whatever it is you want to show
	echo "Hello World, I'm a great Dashboard Widget";
} 

// Create the function use in the action hook
function example_add_dashboard_widgets() {
	wp_add_dashboard_widget('example_dashboard_widget', 'Example Dashboard Widget', 'example_dashboard_widget_function');
}
// Hook into the 'wp_dashboard_setup' action to register our other functions
add_action('wp_dashboard_setup', 'example_add_dashboard_widgets' );

Source: Source

Change WordPress dashboard colors

If you ever wanted to be able to change WordPress dashboard colors (as well as font or even display) without having to edit WordPress core files, you’ll like this hack for sure.
The following example features a basic style change (grey header is replaced by a blue one) but you can easily add as many styles as you wish within the <style> and </style> tags.

function custom_colors() {
   echo '<style type="text/css">#wphead{background:#069}</style>';
}

add_action('admin_head', 'custom_colors');

Provide custom help messages

If you’re building a site for a client and they have problems with some parts of the dashboard, a good idea is to provide contextual help to the client.
The following hack will allow you to add a custom help messages for the blog admin. As usual, you only have to paste the code into your functions.php file.

function my_admin_help($text, $screen) {
	// Check we're only on my Settings page
	if (strcmp($screen, MY_PAGEHOOK) == 0 ) {

		$text = 'Here is some very useful information to help you use this plugin...';
		return $text;
	}
	// Let the default WP Dashboard help stuff through on other Admin pages
	return $text;
}

add_action( 'contextual_help', 'my_admin_help' );

Source: Studio Grasshopper

Remove dashboard widgets according to user role

If you’re owning a multi-user blog, it may be useful to know how to hide some dashboard widgets to keep confidential information in a safe place.
The following code will remove the postcustom meta box for “author” (role 2). To apply the hack on your own blog, just copy the code below and paste it in your functions.php file.

function customize_meta_boxes() {
     //retrieve current user info
     global $current_user;
     get_currentuserinfo();

     //if current user level is less than 3, remove the postcustom meta box
     if ($current_user->user_level < 3)
          remove_meta_box('postcustom','post','normal');
}

add_action('admin_init','customize_meta_boxes');

Source: Smashing Magazine

Reduce amount of post revisions

Post revisions are very useful, but they also clutter your database a lot. In order to save some space, you can consider limiting the amount of post revisions automatically saved by WordPress.
This code has to be pasted in your wp-config.php file, located at the root of your WordPress install.

define( 'WP_POST_REVISIONS', 3 );

Source: WordPress Codex

Disable WordPress Login Hints

When you (or someone else) fails to login on your WordPress dashboard, an error message is displayed. While this can be useful to legit users, it can also give precious information to a potential hijacker.
Paste the code below into your functions.php file to prevent login error messages to be displayed.

function no_wordpress_errors(){
  return 'GET OFF MY LAWN !! RIGHT NOW !!';
}
add_filter( 'login_errors', 'no_wordpress_errors' );

Source: Labnol

PremiumCoding giveaway: 3 premium WordPress themes to win!

A word about PremiumCoding


PremiumCoding offers premium WordPress themes for corporate and personal use. They develop beautiful, professional WordPress themes with a minimal and clean design.

Pricing goes either by individual theme ($29-$39 each) or by membership: a month is priced $69 and a year $89. Both plans grant you the access to all 19 themes to date, theme updates, premium support, and access to all new themes. There’s also a lifetime membership, with no recurring fee, at $269.

PremiumCoding also offers a few freebies that you might want to check out.

How to enter the giveaway


PremiumCoding is generously offering three copies of their newest theme, Britonic, to CatsWhoCode readers. So don’t wait any further and enter our giveaway to try to win one of the three copies of Britonic!

As usual, entering the giveaway is super easy: just leave a comment on this post to let us know that you’re in. In one week, I will randomly pick three lucky winners who will receive their prize directly from the Premium Coding staff, by email.

Exclusive discount

If you’re not the lucky winner of our giveaway, I still have some great news for you: I negotiated an exclusive 25% discount on all Premium Coding products for all my readers.
To use this discount, follow this link and enter the coupon wpcat25pmc at checkout!

Good luck everybody!

Tutorials and resources to learn and master SVG

The Practical Beginner’s Guide to SVG


Are you new to SVG? If yes, this article is a great starting point. It discusses the practical applications, pros and cons, browser support, and also provides a few resources for you to get started in no time.
Read: The Practical Beginner’s Guide to SVG

How to work with SVG icons


One of the most interesting use of the SVG format is definitely for making icons. This article explains in depth how to prepare your icons, make SVG sprites, adding icons to your pages, and styling icons using CSS. A must-read for every serious web designer or front-end developer.
Read: How to work with SVG icons

Optimizing SVGs for Web Use


You probably know that loading speed is a very important factor of the quality of a website. Every element of a web page – images, scripts, stylesheets, and so on – have to be optimized in order to save bandwidth and provide your users the best experience possible.

This article will show you how to optimize your SVG for the web.
Read: Optimising SVGs for Web Use

Inline SVG vs Icon Fonts


I’ve recently showcased some awesome icon fonts that you can use to replace .gif or .png images for icons. But as you’re in the process of mastering the art of SVG, what about a complete comparison of both SVG icons and icon fonts?
Read: Inline SVG vs Icon Fonts

Pure SVG progress circles


Enough theory for now, it’s time to get practical. What about pure SVG progress circles? Here’s a complete, well-written and explained tutorial on how to do it.
Read: Pure SVG progress circles

Distorted Button Effects with SVG Filters


Applying SVG filters on HTML elements gives you some great opportunity to get creative with click interactions. Adrien from Codrops shows us a still kind of experimental, but definitely promising technique to add a distortion effect on buttons using SVG filters.
Read: Distorted Button Effects with SVG Filters

Masking in the Browser with CSS and SVG


Masking is a technique that lets you display selected portions of an element or an image on the screen while hiding the rest. Web developers can use this technique in the browser via the mask property and the SVG mask element. This tutorial will show you how you can use various masking techniques with SVG and CSS.
Read: Masking in the Browser with CSS and SVG

Creative Typography with SVG


SVG allows incredible text manipulation for a top-notch typography. Here’s an article which will show you by the example how your website typography can benefit from SVG.
Read: Creative Typography with SVG

Pro tips for using scalable vector graphics


Let’s finish this round-up with a little guide full of useful tips to embed SVGs, structure your code, use effects, and more. A great addition to your new SVG skills!
Read: Pro tips for using scalable vector graphics

7 tips to instantly make better webforms

Keep it short

However cool you think your form is, the fact is your users don’t like to fill them. As an avid Internet user myself, I have to battle through dozens of forms every week, getting in touch with people, registering new accounts, and so on.

And let me tell you: at least once or twice a week, I don’t submit a form I initially intended to, just because the form is too long and/or asking for info I don’t want to submit. So if you want people to submit your form, keep it short and simple.

Here’s my recommendations on the matter:

  • Just ask what you really need to know
  • Use default choices (if you own a business in the US, most people who’ll get in touch will be from the US as well, so if you’re asking for their country, make sure that “USA” is the default!)
  • Don’t overuse mandatory fields. If someone tries to reach you by email, there’s really no point in requesting a phone number!
  • On registration forms, offer the possibility to register with Facebook and Twitter.

Use Ajax validation


There’s nothing more annoying than filling a long form, submitting it and… have to correct it and submit it over and over again, just because for example the username you’ve chosen has already been taken. I personally remember giving up registering on a few websites because of this.

I already talked on CatsWhoCode about a very useful jQuery plugin named jQuery Form. It makes Ajax validation very easy, so make use of it to provide a better experience to your users.

Make sure it’s mobile friendly


Nowadays, most people are accessing the Internet with a mobile device such as a smartphone or a tablet. This is why you must always make sure that your forms are responsive and mobile-friendly. It’s really annoying when a form isn’t adapted to mobile browsing, and it might prevent many people from actually using your form.

Give people other ways to reach you


Are you on Twitter? Do you have a Facebook page for your site? Then, make use of social networks and provide links to your social media profiles and pages. Emails are great for in-depth, private conversation, but for a first contact, many people nowadays will prefer to use Twitter or Facebook.

Take it easy with captchas


Spam is a nuisance, we all know that. The favorite way of website owners to protect themselves from receiving countless spam emails a day is to use a CAPTCHA. CAPTCHAs aren’t bad by nature, but if you don’t want your users to give up sending your form, please, don’t use those unreadable, brown on black CAPTCHAs. Spam is your problem, not that of your users!

Use the correct HTML5 input types


All modern browsers support HTML5 and its numerous additions to forms input types. Regardless, an incredibly huge amount of websites still use forms that were coded ten years ago.

HTML5 makes it easier for your users to complete forms and is widely supported, so there’s absolutely no reason not to use it. Check the article below for a reminder of the input types introduced by the HTML5 spec.

Answer!

That may sound simple, but actually all of the above tips are meaningless if you fail to answer on time to your visitors’ requests. Things are fast on the internet, and the competition is tough. So if somebody contacts you through your website and hasn’t heard back from you in 24 hours, you can be sure that this person is going to contact your competitor. Take pride in providing top-notch service!

Tutorial: Create a fancy editable table with jQuery and PureCss

There’s a demo available for this tutorial, click here to see.

Getting started

The very first thing to do, indeed, is to create a index.html document on your server or local drive. Paste the following base code into the newly created document, and then save it.

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Editable table</title>
  <style>
    body{ padding: 1% 3%; color: rgb(119, 119, 119); }
    h1{ color:#333 }
  </style>
</head>

<body>
<h1>Editable table example</h1>

</body>
</html>

We now have to get the free tools we’re gonna use in this tutorial. The first one is called Pure.CSS. It’s a very light CSS framework, ideal for small projects. You don’t need to download this one, since it can be directly linked from Yahoo’s servers. So just paste the following in the <head> section of the index.html file you just created:

<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">

The second tool we’re going to use is a simple and sweet jQuery plugin named editableTableWidget. Download the .js file here and drop it on your web server or local hard drive, in the same directory as the index.html file you created.

All good? Now, let’s play a bit with those nifty tools.

The HTML

Since we’re going to create an editable table, the thing to do right now is obviously… to create a HTML table. Here is the one we’re gonna use in this tutorial. It needs to be pasted in the <body> section of your index.html document:

<table id="editable" class="pure-table pure-table-bordered">
    <thead>
        <tr>
            <th>#</th>
            <th>Make</th>
            <th>Model</th>
            <th>Year</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td>1</td>
            <td>Honda</td>
            <td>Accord</td>
            <td>2009</td>
        </tr>

        <tr>
            <td>2</td>
            <td>Toyota</td>
            <td>Camry</td>
            <td>2012</td>
        </tr>

        <tr>
            <td>3</td>
            <td>Hyundai</td>
            <td>Elantra</td>
            <td>2010</td>
        </tr>
    </tbody>
</table>

Have a look at your index.html document: thanks to Pure.CSS, our very basic table looks elegant and professional. If you’d like more information on what Pure.CSS can do for your HTML tables, be sure to check out the related documentation.

Adding jQuery

Our table looks fine, but it’s still very static. Thanks to jQuery and the editableTableWidget plugin, we are going to make it editable.

The first thing to do is to link to jQuery, since the plugin we’re gonna use depends on it. You can either use your own copy of jQuery, or link from Google CDN, as I did below. We also have to link to the mindmup-editabletable.js file we downloaded previously.
Insert the following code in your index.html document, just above the closing </body> tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 
<script src="mindmup-editabletable.js"></script>

Once done, you simply have to make the HTML table editable as shown below. This code goes straight below the scripts you just added.

<script>
	$('#editable').editableTableWidget();
</script>

That’s it. Have a look at what you created: the table is now editable.

Going further

Now that we have a fully functional editable table, let’s go a bit further and see what we can do to make it better. The first thing would be to make sure that specific cells can’t be edited. No big deal here, we simply have to add a class to any <td> element:

<td class="uneditable">...</td>

And then, use the following JavaScript to detect changes on uneditable cells, and prevent it:

$('#editable td.uneditable').on('change', function(evt, newValue) {
	return false;
});

If you want to test this on the demo, try to edit the cell that reads “2010” on the bottom right of the table: as you can see, the value of the cell cannot be edited.

Ultimately, there are strong chances that you’d like to store the entered values into a database. The easiest solution for this would be to use jQuery and Ajax to automatically send the values to a PHP script which will take care of dealing with the data and storing it into a database.

That’s very simple to do, actually, using the jQuery .post() method.

$('#editable td').on('change', function(evt, newValue) {
	$.post( "script.php", { value: newValue })
		.done(function( data ) {
    			alert( "Data Loaded: " + data );
		});	
	;
});

On line 1, we’re using an event listener to check if the value has been changed by the user. If yes, a .post() request containing the newValue variable is sent to a php script (script.php, not included in this tutorial) on the server.

That’s all for today. Hope you enjoyed this tutorial! Don’t hesitate to subscribe to CatsWhoCode newsletter to make sure you won’t miss any upcoming posts!

10 PHP functions and code snippets to work with dates

Get current time, formatted

Super basic function, takes no parameters and returns the current date. This example uses British date formatting, you can change it on line 2.

function nowuk(){
	return date('d/m/Y', time());
}

Format a date

The easiest way to convert a date from a format (here yyyy-mm-dd) to another. For more extensive conversions, you should have a look at the DateTime class to parse & format.

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

Source: Stack Overflow

Get week number from a date

When coding you often find yourself in the need of getting the week number of a particular date. Pass your date as a parameter to this nifty function, and it will return you the week number.

function weeknumber($ddate){
	$date = new DateTime($ddate);
	return $date->format("W");
}

Convert minutes to hours and minutes

Here is a super useful function for displaying times: Give it minutes as an integer (let’s say 135) and the function will return 02:15. Handy!

function convertToHoursMins($time, $format = '%02d:%02d') {
    if ($time < 1) {
        return;
    }
    $hours = floor($time / 60);
    $minutes = ($time % 60);
    return sprintf($format, $hours, $minutes);
}

Get difference between two times

This function takes two dates and returns the interval between those two. The result is set to be displayed in hours and minutes, you can easily change it on line 5 to fit your needs.

function dateDiff($date1, $date2){
    	$datetime1 = new DateTime($date1);
	$datetime2 = new DateTime($date2);
	$interval = $datetime1->diff($datetime2);
	return $interval->format('%H:%I');
}

Check if a date is in the past or in the future

Very simple conditional statements to check if a date is past, present, or future.

if(strtotime(dateString) > time()) {
     # date is in the future
}

if(strtotime(dateString) < time()) {
     # date is in the past
}

if(strtotime(dateString) == time()) {
     # date is right now
}

Source: Art of Web

Calculate age

This very handy function takes a date as a parameter, and returns the age. Very useful on websites where you need to check that a person is over a certain age to create an account.

function age($date){
    $time = strtotime($date);
    if($time === false){
      return '';
    }
 
    $year_diff = '';
    $date = date('Y-m-d', $time);
    list($year,$month,$day) = explode('-',$date);
    $year_diff = date('Y') - $year;
    $month_diff = date('m') - $month;
    $day_diff = date('d') - $day;
    if ($day_diff < 0 || $month_diff < 0) $year_diff-;
 
    return $year_diff;
}

Source: AP PHP

Show a list of days between two dates

An interesting example on how to display a list of dates between two dates, using DateTime() and DatePeriod() classes.

// Mandatory to set the default timezone to work with DateTime functions
date_default_timezone_set('America/Sao_Paulo');

$start_date = new DateTime('2010-10-01');
$end_date = new DateTime('2010-10-05');

$period = new DatePeriod(
	$start_date, // 1st PARAM: start date
	new DateInterval('P1D'), // 2nd PARAM: interval (1 day interval in this case)
	$end_date, // 3rd PARAM: end date
	DatePeriod::EXCLUDE_START_DATE // 4th PARAM (optional): self-explanatory
);


foreach($period as $date) {
	echo $date->format('Y-m-d').'<br/>'; // Display the dates in yyyy-mm-dd format
}

Source: Snipplr

Twitter Style “Time Ago” Dates

Now a classic, this function turns a date into a nice “1 hour ago” or “2 days ago”, like many social media sites do.

function _ago($tm,$rcs = 0) {
   $cur_tm = time(); $dif = $cur_tm-$tm;
   $pds = array('second','minute','hour','day','week','month','year','decade');
   $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
   for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);

   $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
   if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
   return $x;
}

Source: CSS Tricks

Countdown to a date

A simple snippet that takes a date and tells how many days and hours are remaining until the aforementioned date.

$dt_end = new DateTime('December 3, 2016 2:00 PM');
$remain = $dt_end->diff(new DateTime());
echo $remain->d . ' days and ' . $remain->h . ' hours';

Source: Stack Overflow

WPJobster review

Jobster

What is Jobster?

To make it short, Jobster is a WordPress theme that allows you to run a service marketplace, similar to sites like fiverr.com and the like, where people can sell and buy services.

I was offered to test the service, so I had a run at both the front and back-end. I tested the loading speed of the demo theme, which obtained a fairly good score (77 on desktop) on Google PageSpeed Insights.

I also had a quick look at the code, it is well written, documented, and respectful of WordPress coding standards.

Features and pricing

Gorgeous design! One thing I instantly loved with Jobster – it looks good by default. Of course, if you have a website, you want it to look good, right? I haven’t tried to customize the front-end, but it totally looks like a very easy task for anyone with a little experience in WordPress, design and css.

Installation/configuration is included with each license purchase. That’s in my opinion a really good thing, especially for people with very little coding knowledge. Jobster is full of features, so it’s good to know that the team who created it will assist you to install and configure your marketplace.

Jobster is a complete solution that provides you everything you need (the theme itself + the plugins included) to start your online marketplace in just a few days. The cost of entry into this niche has been reduced a lot. That being said, the prices are still way above the average premium theme, which can be a turn-off for some potential buyers. Licenses start at $350 for the webmaster license.

Premium support is included: Jobster support technicians help with taking care of any technical problem that may arise, while you can concentrate on running the business.

One time fee: you pay once, and the theme is yours. No monthly or yearly subscription. Support is limited to 3, 6 or 12 months depending on your license type, but can be extended. Not to mention that the full code source is included, in accordance of WordPress GPL license.

It’s a WordPress theme, so you can extend its functionality with plugins, and if you’re already familiar with WP, running Jobster won’t be a problem at all.

Conclusion

There’s hundreds of WordPress themes released every day, and many of them are poor in terms of design, code or usability. Jobster clearly stands out on that point. It’s not the theme that everyone needs as its purpose is really specific, but if you want to create a service marketplace, I can’t think of a better option at the time I’m writing.

Coding your own would take forever, and other existing scripts don’t run in WordPress. As a devout WordPress user, I admit without any kind of hesitation that I love the fact that Jobster is a WordPress theme and not just a script or another obscure CMS. Using WordPress free plugins, you can implement SEO options, caching and whatever else you may need.

Jobster starts at $350. While this price is above the average price of a WordPress theme, it is incredibly lower than if you hired a coder to design and develop a similar theme.

Pros

  • Good-looking design and solid code
  • Support, installation and configuration included in the price
  • Built within WordPress, so you get all the benefits of the platform
  • Everything you need to create your own service marketplace

Cons

  • Registration is needed to check the online demo
  • Price above the average


And that’s not all, I have some good news for people interested in Jobster: just contact them and mention CatsWhoCode.com and you’ll get a 10% discount!

5 online tools to instantly check the quality of your site

Google pagespeed insights


As most of you already know, nowadays mobile browsing has surpassed desktop browsing. This is why the loading speed of your website is an extremely important factor of its general quality.

Google has created a tool that allows website owners to check how fast their websites are to load. There are countless sites which can help you to check your site speed and hence fix issues, such as Pingdom. The reason I prefer to use Google’s is because the search engine considers website speed an important factor of quality, and the speed of your websites affects your rankings.

→ Visit Google PageSpeed Insights

W3C validator


While probably not a super important factor of quality anymore, valid code is a sign of a web developer who has an attention to detail and pride in their work.

Invalid code doesn’t affect your SEO, and most of the time, it won’t make your user experience worse. But it has to have a balance: sure, 100% valid HTML isn’t as important and “hyped” that it was in 2009. But it still matters.

The reference tool for checking the quality of your HTML markup and CSS code is the good old W3C validator. And if you haven’t checked a document for years, you’ll probably be interested to hear that they have created a new tool called “Nu HTML”.
→ Visit W3C Validator

ScreenFly


If you own a website, you want it to look good. But does it look good on other devices? As you can’t own 5 smartphones, 10 laptops and 5 desktop displays, the best way to check how your website looks on multiples devices and resolutions is to use a tool which allows you to visualize an url under different resolutions.

As often, there’s a lot of different tools competing. My favorite is by far ScreenFly, for its modern and easy-to-use interface as well as its predefined presets
→ Visit ScreenFly

Achecker


According to W3C, “Web accessibility means that people with disabilities can use the Web. More specifically, Web accessibility means that people with disabilities can perceive, understand, navigate, and interact with the Web, and that they can contribute to the Web.” So, in terms of ethics, it’s definitely an important aspect of a quality website.

AChecker is an online tool that checks HTML pages for conformance with accessibility standards to ensure the content can be accessed by everyone.
→ Visit AChecker

WebPagetest


Here’s a free online tool which allows you to run a free website speed test from multiple locations around the globe using real browsers (IE and Chrome) and at real consumer connection speeds.

You can run simple tests or perform advanced testing including multi-step transactions, video capture, content blocking and much more. Your results will provide rich diagnostic information including resource loading waterfall charts, Page Speed optimization checks and suggestions for improvements.
→ Visit WebPageTest

Tutorial: Create a fixed announcement bar for your website

The HTML

The first thing to do is indeed to create the html for displaying our fixed bar. To do so, place the following code at the very end of your html document, before the closing </body> tag.

If you’re using WordPress, you have to edit the footer.php file of the theme you’re using.

<div id="dabar">
    <strong>Don't miss out any post!</strong> <a href="#">Subscribe to our newsletter</a>
</div>

The CSS

Once done with the html bit, open your .css file and paste the following code, then adapt the value of the background and color properties to fit your site color scheme.

#dabar{
	background: rgb(252, 70, 30);
	color: #fff;
	display: block;
	position: fixed;
	bottom: 0;
	width: 100%;
	padding: 10px 0px;
	text-align: center;
}

#dabar a{ 
        color: #fff; 
        text-decoration:underline; 
        font-weight: normal; 
}

There’s really nothing complicated here. We just basically set up a 100% width on the #dabar element, and use the position: fixed and bottom: 0 properties to make the div fixed at the bottom of the page.

If you’d rather have your bar fixed on the top, simply replace bottom: 0 by top: 0.

Now that we added the basic css styling, we still have a few fixes to make to ensure that our bar is gonna look good. The first thing to do is to take care of mobile devices. Obviously, we don’t want our bar to be seen on smaller devices such as smartphones, as it would take a big amount of space and bother reading.

In your .css file, just add the following. If your site is already using media queries, you should just add the #dabar{ display: none; } part to your existing media query.

@media only screen and (max-width: 767px) {
    #dabar{ 
        display: none;
    }
}

One last thing: As the bar is fixed at the bottom of the screen, it’s hiding a bit of your site footer. To prevent this, just find your footer element in your .css style and add a padding as shown below:

#footer{
    padding-bottom: 25px;
}

PHP to display random messages

At the point of the tutorial, we have our message bar. That’s great, but wait, it can be a lot better.

If you’re using the message bar to display promotional offers, you might want to alternate which offer is being displayed to your visitors. Using a little PHP, we can achieve this in no time.

If you’d like to display alternate messages, replace the html code with the following:

<?php 
    $items = array( 'Message #1', 'Message #2' ); 
    shuffle($items); 
?> 

<div id="dabar"><?php echo $items[0]; ?></div>

What we’ve done is really simple: first, we created an array containing all our messages. We then use the shuffle() PHP function to randomize the array. And finally, the first value of the array is displayed.

WordPress users: Display your latest post

If you’re using WordPress, you can use your message bar to display your latest published post. To do so, replace the html code with the following:

<div id="dabar">
<?php
    $args = array( 'numberposts' => '1', 'post_status' => 'publish' );
    $posts = wp_get_recent_posts( $args );
    printf( 'Latest post: <a href="%1$s">%2$s</a>',
             esc_url( get_permalink( $posts[0]['ID'] ) ),
             apply_filters( 'the_title', $posts[0]['post_title'], $posts[0]['ID'] )
    );
    
?>
</div>

7 free alternatives to popular WordPress premium plugins

Mailchimp: MailPoet Newsletter


Most bloggers are building an email list, which is a great thing if you want to make money online with your blog, as email marketing is probably the most efficient way to do so.
Mailchimp and Aweber are the most widely used services to manage email lists and send newsletters. While I’m myself using Mailchimp and definitely recommend the service, if you’re looking for a 100% free solution, you should definitely have a look at Mailpoet Newsletter, a powerful plugin which allows you to manage email lists and send newsletter directly from your WordPress dashboard.
MailPoet Newsletter : Free download

OptinMonster: PopupAlly


OptinMonster has gained a lot of popularity over the past two years for its ability to catch attention of leaving visitors and show them a special offer of an invitation to subscribe to your mailing list.
But starting at $9 a month, OptinMonster is somewhat an investment. Good news for those who don’t want to spend such an amount of money, PopupAlly is a 100% free alternative to OptinMonster. The coolest feature is definitely the “Exit Intent” technology which detects when the user is about to leave, just like OptinMonster does.

There’s also a “pro” version of PopupAlly available, which includes a lot of extra features.
PopupAlly : Free download

Visual Composer: MP Stacks


Visual Composer has grown super popular in the last 12 months, allowing bloggers with little to no coding knowledge to build their own layouts via an intuitive drag and drop editor.

Created by Mint Plugins, MP Stacks is a 100% free alternative to Visual Composer. A great option for those with little budget to create an awesome website.
MP Stacks : Free download

BuySellAds: AdRotate


I’ve been using BuySellAds for over 5 years and have always enjoyed the results. They provide all you need to display ads on your blog and get paid for it. It’s great, but indeed not free, as BSA keeps 25% of your earnings for themselves.

So what about managing your ads yourself? AdRotate is in my opinion the best plugin to do so.
AdRotate : Free download

Monarch: Floating Social Bar


Monarch is a super fast plugin developed by ElegantThemes, which automatically puts a floating bar with social buttons of your choice for your visitors to share your articles. I really love that plugin and recommend it, but if you’re broke, no problem: The Floating Social Bar plugin gives you similar features for free!
Floating Social Bar : Free download

Gravity Forms: Contact Form 7


When it comes to forms plugins, Gravity Forms has been the reference for many years. While it’s for sure a great plugin, I’ve never been that enthusiastic about paying for such a basic feature. My choice has always been Contact Form 7, a free and super flexible plugin which allows you to create as many forms as you need, with no coding required. Forms can be integrated on pages, widgets, posts and even on your theme.
Contact Form 7 : Free download

Ninja Affiliate: SEO Smart Links


Ninja Affiliate is a premium plugin that allows you to define a list of keywords, and automatically turn those keywords in your posts into hyperlinks. The benefit of it is that you can define keywords like “hosting” and turn all occurrences of that keyword into a link to a hosting affiliate program you’re a part of.

Nice, isn’t it? But wait, you don’t need to pay for that plugin. SEO Smart Links does absolutely the same thing (besides cloaking links, but you can use something like redirection for it) and doesn’t cost a dollar.
SEO Smart Links : Free download