Affichage des articles dont le libellé est Sample. Afficher tous les articles
Affichage des articles dont le libellé est Sample. Afficher tous les articles

samedi 12 novembre 2016

How to save time with cron: Basic guide and sample codes



alt="How to save time with cron: Basic guide and sample codes" src="http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2015/04/default-image-500x308_c.jpg" />

What is cron?

Cron is a Linux/UNIX daemon that is designed to execute a command at a predefined time. Since cron is a daemon, once it is executed it does not require any administration from the user. Cron is controlled by a set of files called “cronfiles”, below is a list of common cron commands.

class="border" width="100%" cellspacing="0" cellpadding="1">bgcolor="#DDDDDD" width="200"> Crontab filename bgcolor="#DDDDDD">Install filename as your crontab file.valign="top" width="200">crontab -evalign="top">Edit your crontab file.valign="top" width="200">crontab -lvalign="top">Show your crontab file.valign="top" width="200">crontab -rvalign="top">Remove your crontab file.valign="top" width="200">MAILTO=user@domain.comvalign="top">Emails the output to the specified address.

Each entry into the crontab file will consist of the following six fields separated by a space. The order of the fields along with a brief description of each one is listed below.
minute(s) hour(s) day(s) month(s) weekday(s) command(s)

class="border" width="100%" cellspacing="0" cellpadding="1">bgcolor="#dddddd" width="100"> Fieldbgcolor="#dddddd" width="100">Valuebgcolor="#dddddd">Descriptionvalign="top" width="100">Minutevalign="top" width="100">0-59valign="top">Defines the exact minute the command will execute.valign="top" width="100">Hourvalign="top" width="100">0-23valign="top">Defines the hour of the day the command will execute.valign="top" width="100">Dayvalign="top" width="100">1-31valign="top">Defines the day of the month the command will execute.valign="top" width="100">Monthvalign="top" width="100">1-12valign="top">Defines the month of the year the command will execute.valign="top" width="100">Weekdayvalign="top" width="100">0-6valign="top">Defines the day of the week the command will execute.
Sunday=0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6valign="top" width="100">Commandvalign="top" width="100">Specialvalign="top">The complete command that will be executed.

You can also use an * in place of the numerical character of the first five fields to indicate all legal values. For example, 0 0 * * 1 command, would run a script on every Monday.
Most of this section is only relevant if you are running scripts from the command terminal in Linux/UNIX, if you are using a cPanel please view the “How do I run a cron script from my cPanel” section.

How can I save time with cron?

There are many ways you can use cron to save some but to me the most useful tasks you can schedule are running database and website backup scripts. Both of these jobs can easily be done manually but they are often over looked. With cron you can set them up once and know it will get done.

Below are sample scripts you can use to setup these jobs with cron.

Automatic WordPress Database Backups (Script provided by href="http://tamba2.org.uk/wordpress/cron/" target="_blank">T2)

#Set the 4 variables
#Replace what is AFTER the = with the information from your wp-config.php file

DBNAME=DB_NAME

DBPASS=DB_PASSWORD

DBUSER=DB_USER

#Keep the ” around your address
EMAIL=”you@your_email.com”

mysqldump –opt -u $DBUSER -p$DBPASS $DBNAME > backup.sql
gzip backup.sql
DATE=`date +%Y%m%d` ; mv backup.sql.gz $DBNAME-backup-$DATE.sql.gz
echo ‘Blog Name:Your mySQL Backup is attached’ | mutt -a $DBNAME-backup-$DATE.sql.gz $EMAIL -s “MySQL Backup”
rm $DBNAME-backup-$DATE.sql.gz

Automated Website Backups (Script provided by href="https://help.ubuntu.com/8.04/serverguide/C/backup-shellscripts.html" target="_blank">Ubuntu)

#!/bin/sh

####################################

#

# Backup to NFS mount script.

#

####################################

# What to backup.

backup_files=”/home /var/spool/mail /etc /root /boot /opt”

# Where to backup to.

dest=”/mnt/backup”

# Create archive filename.

day=$(date +%A)

hostname=$(hostname -s)

archive_file=”$hostname-$day.tgz”

# Print start status message.

echo “Backing up $backup_files to $dest/$archive_file”

date

echo

# Backup the files using tar.

tar czf $dest/$archive_file $backup_files

# Print end status message.

echo

echo “Backup finished”

date

# Long listing of files in $dest to check file sizes.

ls -lh $dest

 

*Disclaimer: We are not a responsible if the script fails to run correctly or if you set it up incorrectly. If you have any questions or concerns about the script or how to set it up the best contact will be your host provider.

How do I run a cron script from my cPanel?

1. Log into you cPanlel

2. Locate the “cron jobs” icon (This is generally in the advanced section).

class="border" src="http://www.webhostingsecretrevealed.com/images/2011/1116-1.jpg" alt="" />

3. Enter your E-Mail address if you would like a copy of the crop output to be emailed to you.

class="border" src="http://www.webhostingsecretrevealed.com/images/2011/1116-2.jpg" alt="" />

4. Choose when you would like your cron script to run. (Choosing an item from the “Common Settings” dropdown box will fill in the fields for you.)

class="border" src="http://www.webhostingsecretrevealed.com/images/2011/1116-3.jpg" alt="" />

5. Enter the path of the script you would like to run. (Note: You will need to upload your script file to your server, for more information please see below – “How do I upload my script file” section for details.)

class="border" src="http://www.webhostingsecretrevealed.com/images/2011/1116-4.jpg" alt="" />

6. Click “Add New Cron Job”

class="border" src="http://www.webhostingsecretrevealed.com/images/2011/1116-5.jpg" alt="" />

7. Your cron job should now be listed under “Current Cron Jobs”.

class="border" src="http://www.webhostingsecretrevealed.com/images/2011/1116-6.jpg" alt="" />

How do I upload my script file?

class="border" src="http://www.webhostingsecretrevealed.com/images/2011/1116-7.jpg" alt="" />

  1. From your cPanel choose “File Manager”
  2. Next choose “Home Directory” then click “Go”
  3. Now choose “Upload”.
  4. Set your File Permissions to 755
  5. Click “Browse”
  6. Browse to the folder that has your script and click on it, and then click “Open”.

Note: Your cPanel may be setup differently than the one shown above but the overall concepts should still be the same.


Page 26 – Web Hosting Secret Revealed




15 Cool JavaScript Sample Snippets



alt="15 Cool JavaScript Sample Snippets" src="http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2015/04/default-image-500x308_c.jpg" />

A Quick Overview On JavaScript

JavaScript is used everywhere online these days – to improve website interactivity, to validate information, and/or to improve a website outlooks. JavaScript first appeared in 1995 and has come a long way since then in terms of being accepted and how it is used. The syntax used in JavaScript was strongly influenced by C; but Java, Pearl, Python, and Scheme also played its part too.

What Is JavaScript?

There’s an old YouTube clip answers the question well. Here goes.

class="border" width="600" height="437" src="http://www.youtube.com/embed/qtzjzMsJiO8" frameborder="0" allowfullscreen>

Beginner Tips: What You Need To Know?

For starters, a few basics you need to know are:

  • JavaScript can be turned off in the browser
  • JavaScript will run each time a page is loaded
  • JavaScript takes time to load on a slow Internet connection
  • JavaScript is still ran from cached pages
  • You can host JavaScript within a web page or externally from a .js file
  • JavaScript is completely different than Java

It is also important to understand that JavaScript will actually lead to disaster when it’s used in a wrong way. Poorly configured and sloppy coded JavaScripts will slow your website and damage the overall site navigation. This in turn affect the return rate of your visitors (due to bad user experience) as well as search engine rankings (due to slow website response rates).  To help validate my case here, put yourself in the shoes of a viewer. If a website you were visiting loaded slowly, was difficult to navigate, and in overall, unappealing – would you return to the site? I wouldn’t.

Below is a small list of things to think about when adding JavaScript to your website.

  • Is JavaScript required for the site to function properly?
  • What will the site look like if the JavaScript was blocked?
  • Will the JavaScript harm the server performance?
  • Will adding the JavaScript help move your site in the direction you want it to go?

No, I am not trying to scare you away with these points. In fact, don’t be afraid to use JavaScript on your websites as it provides tons benefits and, as mentioned, it’s used by the majorities. The key point I am trying to get across here is don’t just keep adding JavaScript features to a site when they are unnecessary. Some sites are will need more JavaScript than the rest; some just need less – Just because one site is doing it doesn’t mean you should do the same.

Freebies: 15 Cool JavaScript Snippets For Your Website

src="http://www.webhostingsecretrevealed.com/images/2012/0306-2.jpg" alt="JavaScript Snippet" class="border" />

Now, let’s get down to the stuffs that you came here for – below is a list of 15 JavaScript snippets that will enhance your site in either functionality or appearance. The code will be broken down into two sections, the head and body or .js file. If no section title is given then it is not needed for that particular snippet.

Understanding HTML5 Video

Quick Sample

<script type="text/javascript">

function understands_video() {
return !!document.createElement(‘video’).canPlayType; // boolean
}

if ( !understands_video() ) {
// Must be older browser or IE.
// Maybe do something like hide custom
// HTML5 controls. Or whatever…
videoControls.style.display = ‘none’;
}

</script>

What does the JavaScript snippet do?


This little snippet will prevent your website from trying to display a video that the browser cannot support, saving you bandwidth and processing power.

JavaScript Cookies/>

Quick Sample

<script type="text/javascript">

/**

* Sets a Cookie with the given name and value.

*

* name       Name of the cookie

* value      Value of the cookie

* [expires]  Expiration date of the cookie (default: end of current session)

* [path]     Path where the cookie is valid (default: path of calling document)

* [domain]   Domain where the cookie is valid

*              (default: domain of calling document)

* [secure]   Boolean value indicating if the cookie transmission requires a

*              secure transmission

*/                        

function setCookie(name, value, expires, path, domain, secure) {

    document.cookie= name + "=" + escape(value) +

        ((expires) ? "; expires=" + expires.toGMTString() : "") +

        ((path) ? "; path=" + path : "") +

        ((domain) ? "; domain=" + domain : "") +

        ((secure) ? "; secure" : "");

}

</script>

 

<script type="text/javascript">

/**

* Gets the value of the specified cookie.

*

* name  Name of the desired cookie.

*

* Returns a string containing value of specified cookie,

*   or null if cookie does not exist.

*/

function getCookie(name) {

    var dc = document.cookie;

    var prefix = name + "=";

    var begin = dc.indexOf("; " + prefix);

    if (begin == -1) {

        begin = dc.indexOf(prefix);

        if (begin != 0) return null;

    } else {

        begin += 2;

    }

    var end = document.cookie.indexOf(";", begin);

    if (end == -1) {

        end = dc.length;

    }

    return unescape(dc.substring(begin + prefix.length, end));

}

</script>

 

<script type="text/javascript">

/**

* Deletes the specified cookie.

*

* name      name of the cookie

* [path]    path of the cookie (must be same as path used to create cookie)

* [domain]  domain of the cookie (must be same as domain used to create cookie)

*/

function deleteCookie(name, path, domain) {

    if (getCookie(name)) {

        document.cookie = name + "=" +

            ((path) ? "; path=" + path : "") +

            ((domain) ? "; domain=" + domain : "") +

            "; expires=Thu, 01-Jan-70 00:00:01 GMT";

    }

}

</script>

What does the JavaScript snippet do?

This snippet is a little long but very useful, it will allow your site to store information on the viewer’s computer then read it at another point in time. This snippet can be used in many different ways to accomplish different tasks.

Preload your images/>

Quick Sample

<script type="text/javascript">

var images = new Array();

function preloadImages(){

    for (i=0; i < preloadImages.arguments.length; i++){

         images[i] = new Image();

        images[i].src = preloadImages.arguments[i];

    }

}

preloadImages("logo.jpg", "main_bg.jpg", "body_bg.jpg", "header_bg.jpg");

</script>

What does the JavaScript snippet do?

This snippet will prevent your site from having that awkward time when it is only displaying part of the site; this not only looks bad but is also unprofessional. All you have to do is add your images to the preloadImages section and you are ready to roll.

E-mail Validation

Quick Sample

Head:

<script type="text/javascript">
function validateEmail(theForm) {
if (/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/.test(theForm.email-id.value)){
return(true);
}
alert("Invalid e-mail address! Please enter again carefully!.");
return(false);
}
</script>

Body:

<form onSubmit="return validateEmail(this);" action="">
E-mail Address:
<input type="text" name="emailid" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>

What does the JavaScript snippet do?

This snippet will validate that a properly formatted E-mail address is entered in a form, it cannot guarantee that the E-mail address is real, there is no way to check for that with JavaScript.

No Right-Click

Quick Sample

<script type="text/javascript">
function f1() {
  if(document.all) { return false; }
}
function f2(e) {
  if(document.layers || (document.getElementById &! document.all)) {
    if(e.which==2 || e.which==3) { return false; }
  }
}
if(document.layers) {
  document.captureEvents(Event.MOUSEDOWN);
  document.onmousedown = f1;
}
else {
  document.onmouseup = f2;
  document.oncontextmenu = f1;
}
document.oncontextmenu = new function("return false");
</script>

What does the JavaScript snippet do?

This snippet will prevent the viewer from being able to right-click on your page. This can discourage the average user from borrow images or code from your site.

Display Random Quotes

Quick Sample

Head:

<script type="text/javascript">
  writeRandomQuote = function () {
    var quotes = new Array();
    quotes[0] = "Action is the real measure of intelligence.";
    quotes[1] = "Baseball has the great advantage over cricket of being sooner ended.";
    quotes[2] = "Every goal, every action, every thought, every feeling one experiences, whether it be consciously or unconsciously known, is an attempt to increase one’s level of peace of mind.";
    quotes[3] = "A good head and a good heart are always a formidable combination.";
    var rand = Math.floor(Math.random()*quotes.length);
    document.write(quotes[rand]);
  }
  writeRandomQuote();
</script>

Body:

<script type="text/javascript">writeRandomQuote();</script>

What does the JavaScript snippet do?

Ok so this is not a snippet that all sites would use but it can be used to display more than just random quotes. You can change the content ok the quotes to whatever you want and have random images or text displayed anywhere on your site.

Previous/Next Links

Quick Sample

<a href="javascript:history.back(1)">Previous Page</a> | <a href="javascript:history.back(-1)">Next Page</a>

What does the JavaScript snippet do?

This snippet is great if you have multiple pages on an article or tutorial. It will allow the user the browse between the pages with ease. It is also small and light weight from a resource point of view.

Bookmark a Page

Quick Sample

<a href="javascript:window.external.AddFavorite(‘http://www.yoursite.com’, ‘Your Site Name’)">Add to Favorites</a>

What does the JavaScript snippet do?

This snippet will allow the user to bookmark your page with ease; all they have to do is click the link. Its little features like this that can increase your viewers overall experience.

Easy Print Page Link

Quick Sample

<a href="javascript:window.print();">Print Page</a>

What does the JavaScript snippet do?

This little link will allow your views to easily print your page. It utilizes the quick print feature already setup by your browser and utilizes no resources until it is clicked.

Show Formatted Date

Quick Sample

Head:

<script type="text/javascript">
  function showDate() {
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //months are zero based
    var curr_year = d.getFullYear();
    document.write(curr_date + "-" + curr_month + "-" + curr_year);
  }
</script>

Body:

<script type="text/javascript">showDate();</script>

What does the JavaScript snippet do?

This snippet will allow you to display the current date anywhere on your webpage and does not need to be updated. Simply put it in place and forget about it.

Comma Separator

Quick Sample

Head:

<script type="text/javascript">
function addCommas(num) {
  num += ”;
  var n1 = num.split(‘.’);
  var n2 = n1[0];
  var n3 = n1.length > 1 ? ‘.’ + n1[1] : ”;
  var temp = /(d+)(d{3})/;
  while (temp.test(n2)) {
    n2 = n2.replace(temp, ” + ‘,’ + ”);
  }
  var out = return n2 + n3;
  document.write(out);
}
</script>

Body:

<script type="text/javascript">addCommas("4550989023");</script>

What does the JavaScript snippet do?

This snippet would be used mainly by sites that use numbers often. This snippet will keep your numbers looking the same across the board. All you have to do is copy the body line where you want to add a number and replace the number there with your number.

Get the Display Area of a Browser/>

Quick Sample

<script type="text/javascript">

<!–

var viewportwidth;

var viewportheight;

// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

if (typeof window.innerWidth != ‘undefined’)

{

      viewportwidth = window.innerWidth,

      viewportheight = window.innerHeight

}

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

else if (typeof document.documentElement != ‘undefined’

     && typeof document.documentElement.clientWidth !=

     ‘undefined’ && document.documentElement.clientWidth != 0)

{

       viewportwidth = document.documentElement.clientWidth,

       viewportheight = document.documentElement.clientHeight

}

// older versions of IE

else

{

       viewportwidth = document.getElementsByTagName(‘body’)[0].clientWidth,

       viewportheight = document.getElementsByTagName(‘body’)[0].clientHeight

}

document.write(‘<p>Your viewport width is ‘+viewportwidth+’x’+viewportheight+'</p>’);

//–>

</script>

What does the JavaScript snippet do?

This snippet will allow you to get the width and height of the display area in your views browser. This will give the designer the ability to create and use different displays based on the size of the user’s browser window.

Redirect with Optional Delay

Quick Sample

<script type="text/javascript">

setTimeout( "window.location.href =

‘http://walkerwines.com.au/’", 5*1000 );

</script>

What does the JavaScript snippet do?

This snippet will allow you to redirect your viewers to another page and it has the option of setting a delay. The use of this snippet is pretty self-explanatory and it is a very valuable tool to have in your belt.

Detect iPhones

Sample

<script type="text/javascript">

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {

    if (document.cookie.indexOf("iphone_redirect=false") == -1) {

        window.location = "http://m.espn.go.com/wireless/?iphone&i=COMR";

    }

}

</script>

What does the JavaScript snippet do?

This snippet will allow you to detect if your viewer is on an iPhone or iPod allowing you to display different content to them. This snippet is invaluable with how large the mobile market is and it is only going to continue to grow.

Print Message to Status Bar

Quick Sample

<script language="javascript" type="text/javascript">
<!–
   window.status = "<TYPE YOUR MESSAGE>";
// –>
</script>

What does the JavaScript snippet do?


This little snippet will allow you to print a message to the status bar. You can display recent or important news in an area the will catch the eye of the user.


Page 25 – Web Hosting Secret Revealed




How to Make Good Use of CSS3 Animations: Tutorial, Sample Codes, and Examples



alt="How to Make Good Use of CSS3 Animations: Tutorial, Sample Codes, and Examples" src="http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-6-500x307_c.jpg" />

When we use JS and jQuery we have full control over the animations and we can create some awesome effects, but the price is quite high. Processing time, cross-browser compatibility (mobile devices, for example, are quite different when it comes to JS) and the code complexity itself are points that we should keep in mind while creating animated interfaces.

So, today we’ll see how to avoid JS by using CSS Animations and Transitions. We’ll discuss from the very basic steps to some awesome effects, like accordion panels and animated sub-menus.

Grab a seat, you notepad and a real browser (anything but IE) and let’s get started.

Warming up

We have quite a few advantages (and disadvantages as everything in our lives) in using CSS animations. If you need to sell those to your boss or client, this is what you should keep in mind:

  • They are potentially faster, since they can make use of hardware acceleration (as HTML5 implementations)
  • They’ll perform better in mobile devices and won’t need specific code to track touch events
  • JS needs to be interpreted by the browser and the possibilities to break the browser are much bigger. So when CSS fails, it fails silently while JS can break the entire page
  • They have quite a good browser support (this site will help you checking specific stats on that: href="http://caniuse.com/#search">http://caniuse.com/#search )

Examples of CSS3 Animations

Before we get started on the meat of this post, let’s look at some beautiful animations made in pure CSS.

Pure CSS Twitter Fail Whale

style="text-align: center;">class="aligncenter wp-image-1745 border" alt="Animated Failed Whale" src="http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-5.jpg" width="750" height=" " srcset="http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-5.jpg 600w, http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-5-300x158.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" />

class="meteor-icon" style="font-size:12px !important;">
class="icon-angle-right" style="color:inherit !important;">
 Made by Steven Dennis, href="http://www.subcide.com/experiments/fail-whale/" target="_blank">see this in action.

style="text-align: center;">Pure CSS Scrolling Coke Can
class="aligncenter wp-image-1746 border" alt="CSS 3 Animation Examples: Scrolling Coke Can" src="http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-6.jpg" width="750" srcset="http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-6.jpg 600w, http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-6-300x184.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" />

class="meteor-icon" style="font-size:12px !important;">
class="icon-angle-right" style="color:inherit !important;">
Made by Roman Cortes, title="Scrolling Coke Can" href="http://www.romancortes.com/ficheros/css-coke.html" target="_blank">see this in action.

Pure CSS Walking Man

style="text-align: center;">class="aligncenter wp-image-1747 border" alt="CSS 3 Animation Examples: The Walking Man" src="http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-7.jpg" width="750" srcset="http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-7.jpg 600w, http://whsr.webrevenueinc1.netdna-cdn.com/wp-content/uploads/2013/06/0611-7-300x182.jpg 300w" sizes="(max-width: 600px) 100vw, 600px" />

class="meteor-icon" style="font-size:12px !important;">
class="icon-angle-right" style="color:inherit !important;">
 Made by Andrew Hoyer, title="The Walking Man" href="http://andrew-hoyer.com/experiments/walking/" target="_blank">see this in action.

Getting Your Hands Dirty

Let’s start the code. We’ll use a lot the CSS pseudo classes to trigger the animation. To be honest, a lot of developers recommend you using JS to activate and de-activate animations, but here we’ll see the easier way:

#test {
background: red;
}
#test:hover {
background: green;
}
#test:active {
background: blue;
}
#test:target {
background: black;
}

We have a few other pseudo-classes to use, but you’ve got the idea! So here is what happens if you click the #test element (assuming it’s a link):

  • Normal state: Background will be red
  • Hover: When the mouse enters element area it’ll have a green background
  • Active: When you click the cursor on it and while the mouse button is still pressed the background color will be blue
  • Target: When current page has the #test in the URL this element will be black

Each one of these can be used for CSS animations, for example you could create 2 links to activate and deactivate the CSS animation making use of the target pseudo element with this code:

<a href='#test'>activate</a>
<a href='#'>deactivate</a>

CSS Transitions

CSS transition will change from the initial to the end state smoothly. So you’ll define in the main selector using the “transition” property the time and each property that will be affected and how the animation should be. Let’s see an example:

.test {
/*transition-property duration timing-function,*/
color: blue;
transition: color 2s, font-size 2s ease-out;
}
.test:hover {
color: red;
}
.test:active {
font-size: 200%;
}

When you hover the .test element it’ll change gradually the color from blue to red (what a nice palette, huh?). When you click the element, the font size will gradually increase to 200% of the default font size.

We have also the “transition timing” property, set as ease-out, that how the “time” available for the animation will be spent. Here are the possible values:

  • Linear: Same speed from the beginning to the end
  • Ease-in: Slow start
  • Ease-out: Slow end
  • Ease: Slow start, fast in the middle, then slow end
  • Ease-in-out: Slow start, slow end
  • Cubic-bezier(a,b,c,d): Custom speed

The cubic Bezier function will create a custom animation with 4 numbers that varies from 0 to 1, representing the mathematical curve for animation speed X duration.

For better browser compatibility you should consider using the vendor prefixes for opera, Firefox, and webkit like this:

div {
width: 400px;
-o-transition: width 2s;
-moz-transition: width 2s;
-webkit-transition: width 2s;
transition: width 2s;
}

Also, you could make use of the media queries to define different transitions depending on browser width (mobile devices, tablets). This is a simple example:

body {
font-size: 1em;
}
@media screen and (max-width: 800px) {
body {
font-size: 0.8em;
}
}
@media screen and (max-width: 400px) {
body {
Font-size: 0.7em;
}
}

Here the font size will be changed suddenly when you increase the browser width. This code will prevent that from happening, giving a much smoother transition:

body {
-o-transition: font-size .5s linear;
-moz-transition: font-size .5s linear;
-webkit-transition: font-size .5s linear;
transition: font-size .5s linear;
}

You could use this also if you have different displays or sizes for portrait / landscape, if you want to change widths, colors, paddings, menu display.

CSS Animation – The Real Fun Starts

The animation is a sequence of transitions defined in a single selector. To define CSS animations you’ll need to follow 2 steps.

The @keyframe rule is used to define a sequence of animation steps, and it’s defined by a unique name and the styles that describe how this animation works. As usual we’ll need some vendor prefixes, like in this example:

/*the same code for each vendor*/
@-o-keyframe my-animation { ...
@-moz-keyframe my-animation { ...
@-webkit-keyframe my-animation { ...
/*animation name*/
@keyframe my-animation {
/*frame selector*/
0% {
/*frame style*/
Left: 0px;
Top: 0px;
}
25% {
Left: 200px;
Top: 0px;
}
50% {
Left: 200px;
Top: 200px;
}
75% {
Left: 0px;
Top: 200px;
}
100% {
Left: 0px;
Top: 0px;
}
}

So, each style is defined by the frame / timeframe (like those frames from a flash animation) as a percentage and the styles that should be applied there. This keyframe, for example says that the element will move to the left, then top, then right, then bottom.

After you’ve followed the step 1 and created your keyframe you can actually apply it to an element. Then we’ll use pretty much the same logic as we’ve done with the CSS transition, the difference is that now our “transition” is a much complex animation.

To apply it we’ll use the animation property and it has 7 sub-properties:

  • Name: that unique identifier
  • Duration: How long will it take from 0% to 100%
  • Timing-function: pretty much the same as the transition timing function
  • Delay: How long will it take to start the 0%
  • Iteration-count: How many repetitions will we have(“infinite” for a infinite loop)
  • Direction: normal or alternate (reverse)
  • Play-state: if the animation is running or paused

This will apply our animation to the #test element when it is the page’s target:

#test:target {
/*animation-name | duration | timing-function | delay |iteration-count | direction | play-state */
animation: my-animation 10s linear 0s infinite normal running;
}

With this in mind we can create a few awesome examples.

CSS Only Accordion

We’ll create collapsible panels making use of the CSS animations. Here is the basic HTML structure:

<div class="accordion">
<a href="#tab1">Tab 1</a><div id="tab1"><p>TEXT 1</p></div>
<a href="#tab2">Tab 2</a><div id="tab2"><p>TEXT 2</p></div>
<a href="#tab3">Tab 3</a><div id="tab3"><p>TEXT 3</p></div>
</div>

This will just create the panels and the link that will trigger each one of them. And here is where the magic happens:

/* any div that is inside of the accordion*/
.accordion div {
/*is hidden by default */
height: 0;
overflow: hidden;
/* the black magic */
transition: height 1s;
}
/*when the mentioned div is the target */
.accordion div:target {
/*height:auto won’t work, but this will work fine*/
height: 80px;
}

Pretty simple, huh? And you’ve spent your entire life using JS for this? :)

CSS Only Menu with Submenus

And this is another rather simple application. You certainly have a navigation menu in your site, and often we need to use some submenus there. The best way to show and hide items is using jQuery, right? Well, think again after you test this code:

<nav>
<ul>
<li><a href='#item1'>Item 1</a><div><ul>
<li><a href='#item11'>Item 1.1</a></li>
<li><a href='#item12'>Item 1.2</a></li>
</ul></div></li>
<li><a href='#item2'>Item 2</a><div><ul>
<li><a href='#item21'>Item 2.1</a></li>
<li><a href='#item22'>Item 2.2</a></li>
</ul></div></li>
</ul>
</nav>

And the wizardry begins here:

a {
/* just making the links a tad better */
display: block;
padding: 4px;
}
nav {
text-align: center;
}
/* any menu (including the main one)*/
nav ul {
display: inline-block;
list-style: none;
}
nav>ul>li {
/* horizontal items (vertical will work fine too) */
float: left;
}
nav li div {
/*collapsing any sub-menu*/
height: 0;
overflow: hidden;
/* Houdini feelings */
transition: height 1s;
}
nav li:hover>div {
height: 56px;
}

Summing Up

This is certainly just a getting started guide. There are a lot of other cool effects that can be done using CSS only animations and a lot of things certainly yet to come.

So, have you used this before? Can you think of another good application for CSS animations? Share your thoughts using the comments!


Page 18 – Web Hosting Secret Revealed