Bounce Effect in CSS Only Using CSS3

Ever wanted to have a nice bouncy effect when hovering over something without the use of javascript or hard to learn advanced code?
Use this for your HTML:

1
2
3
    <div class="bounce-cnt">
        <div class="bounce-r" id="the-button">asdf</div>
    </div>

And complement with this for your CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@keyframes hover-over {
    0% {padding: 10px; left: 0px; top: 0px; opacity: 0.7; }
    50% {padding: 16px; left: -6px; top: -6px; opacity: 1; }
    100% {padding: 13px; left: -3px; top: -3px; opacity: 1; }
}
@-webkit-keyframes hover-over {
    0% {padding: 10px; left: 0px; top: 0px; opacity: 0.7; }
    50% {padding: 16px; left: -6px; top: -6px; opacity: 1; }
    100% {padding: 13px; left: -3px; top: -3px; opacity: 1; }
}
@keyframes hover-out {
    0% {padding: 13px; left: -3px; top: -3px; opacity: 1; }
    50% {padding: 16px; left: -6px; top: -6px; opacity: 1; }
    100% {padding: 10px; left: 0px; top: 0px; opacity: 0.7; }
}
@-webkit-keyframes hover-out {
    0% {padding: 13px; left: -3px; top: -3px; opacity: 1; }
    50% {padding: 16px; left: -6px; top: -6px; opacity: 1; }
    100% {padding: 10px; left: 0px; top: 0px; opacity: 0.7; }
}

.bounce-cnt {
    position: relative;
}
.bounce-r {
    animation-name: hover-out;
    animation-duration: 0.2;
    animation-timing-function: linear;
    animation-fill-mode: forwards;
    -webkit-animation-name: hover-out;
    -webkit-animation-duration: 0.2s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-fill-mode: forwards;
    position: absolute;
    top: 0;
    left: 0;
}
#the-button {
    border: 5px solid #000;
    background: #eee;
}
.bounce-r:hover {
    animation-name: hover-over;
    animation-duration: 0.2;
    animation-timing-function: linear;
    animation-fill-mode: forwards;
    -webkit-animation-name: hover-over;
    -webkit-animation-duration: 0.2s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-fill-mode: forwards;
}

But you might say to yourself… “That’s a lot of CSS for one little effect”. That’s fine. Here’s why.
1. You’re not tying up the JS processing.
2. All you have to do is add class to a parent and child pair to make it look and work great, every time, without making the effort of re-writing bouncy code for every element.

Cheers!

Clear floats with overflow: hidden

Lately, I’ve seen a trend of programmers adding on new elements to pages in order to add a class to them to clear all of the floated elements in a container. Why? Simply use overflow hidden on the parent, and like a miracle, bam! The container becomes aware of all of the children elements.

The old way:

1
2
3
4
5
6
7
<ul>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li class="clearfix"></li>
</ul>
1
2
3
4
5
6
li {
    float: left;
}
.clearfix {
    clear: both;
}

The old way is not as effective, since we have to add additional elements that do not show anything. Their only purpose is to fix a css style. Why not do it in css? This method also adds what seems like an additional line that makes it seem like you have bottom margin, or padding. Too much to maintain and fix. Additionally, I believe at the time of this writing, google looks for empty elements and dings you if you don’t put anything in them. Validate your HTML. Be a good programmer.

The new way:

1
2
3
4
5
6
<ul>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
</ul>
1
2
3
4
5
6
ul {
    overflow: hidden;
}
li {
    float: left;
}

Who’s JSON?

J. S. O. N. Actually

Not sure where I’m going with this, but here we go. I like JSON (JavaScript Object Notation). What’s that, you say? You mean, who’s that? Oh, wait. No, it’s ‘what’s that’.

What I’d like to start with is something experimental. Let’s focus on the idea that there is a back-end, and a front-end to any development, especially web development, and especially web application development. What if both sides could simply just communicate with itself via JSON. Why JSON? Because JSON is super light weight for transferring data. What kind of data, you ask? Any kinds. Sure, we could render out code via an AJAX call as HTML, but all those little extra tags are overhead. JSON keeps it simple with only one or two additional characters per variable or value. Let me show you what I mean.

1
var myObject = { "person" : { "fname" : "John ", "lname" : "Donson"} };

Notice what happens in the block of code above. I’ve specified an object with enough information to arrive at the conclusion that this data is related to a person, and their name is John Donson.

jQuery can easily do this JSON encoding from arrays, strings, etc. You just need to pass it the variable:

1
var myObject = $.parseJSON( '{ "person" : { "fname" : "John ", "lname" : "Donson"} }' );

Please note that I’m using double quotes inside the object itself. This is proper JSON format. Escape any single quotes with backslashes. This gives us an object that we can easily inspect in the console log of Firefox.

All right, now that we understand who JSON is, let’s have fun with him.

HTML5 Kicks in

Wouldn’t it be great if we could use HTML5 to send some data to JavaScript who can in turn send the data to the backend (PHP), who can then get some data from a database and return back some JSON code that we can use back in JS to manipulate elements in HTML5?

Wow, I mean, why even go down this road? Simple. Large amounts of data to be processed. PHP may be fast at 300 requests per second, but HTML is even faster, with 1000 requests per second. The idea is to develop for online applications. Such as, a game, or management systems.

Let’s start from the top. Here come’s < a >.

1
<a href="javascript:void(0);" class="jsonCall" data-get='{"url":"/ajax/main.php","data":{"var1":1,"var2":2}}'>Click me!</a>

Whoa, why all this? Let me break it down.

– The void call in the JS call is to make sure older browsers don’t show a white page when clicked.
– We’ve added a class because we want to identify any element with an action. Doesn’t have to be an < a > element.
– data-get is our HTML5 way of introducing data that we will need. This is our JSON data that we will send from JS through our AJAX call.

Let’s see where this takes us.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(document).ready(function(){
    $('.jsonCall').on('click',function() {
        var queryVars = $(this).attr('data-get');
        var qJSON = $.parseJSON(queryVars);
        var qString = "internal=true";
        for (data in qJSON.data) {
            qString += "&"+data+"="+qJSON.data[data];
        }
        $.ajax({
            url: qJSON.url,
            type: 'post',
            data: qString,
            dataType: 'JSON'
        });
    });
});

This is the entire code we need to parse out our data-get attribute value and send it out for processing. Let’s put what we did into practice.

Practice Makes Improvement, Because No One is Perfect

Let’s say we want to load a list o thumbnails with descriptions and links to another page. So, let’s set up the scenario.

What we need:
– link
– thumb
– text

There’s the classic way and try to render everything out on the backend, and spew out some static html that can be placed inside our “container” whatever that container will be.

Why not make it smarter, and just send a request for the items you need. Let’s say you need 16 thumbs because that’s how many thumbs will be on the page at once. Yes, you can always change this number, but 16 is perfect for a 4×4 display of thumbs.

First, we need to understand what our content might look like. It will probably look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<ul>
    <li>
        <a href="">
            <img src="" />
            <span></span>
        </a>
    </li>
    <li>
        <a href="">
            <img src="" />
            <span></span>
        </a>
    </li>
    ...
</ul>

Ok, it will be a little more intricate than that, but here’s the reason to load your content with JSON. All of this above is simply overhead. None of our data has been loaded yet. There IS no data! So, with all this effort of rendering out, we got back a big fat nothing.

Why not templat-ize the results? It would make much more sense. Why not load the template HTML content inside our current document so we can just use it? Since it will be used anyway on the page, load it up, but keep it hidden.

1
2
3
4
5
6
7
8
<script id="content-list-item" type="text/x-jquery-tmpl">
    <li>
        <a href="[[url]]">
            <img src="[[thumb]]" />
            <span>[[text]]</span>
        </a>
    </li>
</script>

This would allow us to get the content via the jQuery.html() function, replace the values inside the double brackets, and append this element to the container.

Doesn’t make sense yet? Let’s compare the old way we used to do things. If we had a loop of items on a page, we would render everything at the php level right after we got the data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$qty = $_POST['qty'];
$retVal = array();

for ($itemCount = 0; $itemCount < $qty; $itemCount++) {
    ?>
    <li>
        <a href="http://www.motortrend.com/roadtests/oneyear/coupe/1302_2013_scion_fr_s_arrival/">
            <img src="http://i2.squidoocdn.com/resize/squidoo_images/-1/lens10584771_1271704447MARIO_thumbnail.jpg" />
            <span>2013 Scion FR-S Arrival</span>
        </a>
    </li>
    <?php
}
?>

This would be fine, if the data would remain minimal, but where are your alt tags, title tags, what if you use itemprops for SEO results. All that is additional overhead.

Our template contains almost the same amount data returned as JSON. The reason being is that we’re not returning

1
<a href="

as data, but we’re most likely returning

1
{"

instead. Less code already.

But, you say, the difference is not that great. We went from 236 bytes to 258 bytes. It’s not a huge difference. It’s about 9%. I’m not impressed.

Ok, what if you do add those additional items, like title, alt, propitem, etc… And what if you have additional wrappers and other overhead HTML that repeats? Your template only includes this once. The rendered version of your code returns this 16 fold. Let’s see the difference between.

235 to 305!!! How’s 30% increase in your data for a significant enough number?

In Conclusion

So, when comparing the two methods, you notice that our template has been increased by a few bytes.

1
2
3
4
5
6
7
8
<script id="content-list-item" type="text/x-jquery-tmpl">
    <li itemprop="stuff">
        <a href="[[url]]" itemprop="url" title="[[text]]">
            <img src="[[thumb]]" itemprop="image" title="[[text]]" alt="[[text]]" />
            <span>[[text]]</span>
        </a>
    </li>
</script>

Our JS has not increased since we’re just reusing the same references for the alt, title, etc tags.

While the oldmain.php rendering file has increased a bit more than the template file, this repeats several times, significantly increasing the size of data transferred back to the client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
$qty = $_POST['qty'];
$retVal = array();

for ($itemCount = 0; $itemCount < $qty; $itemCount++) {
    ?>
    <li itemprop="stuff">
        <a href="http://www.motortrend.com/roadtests/oneyear/coupe/1302_2013_scion_fr_s_arrival/" itemprop="url" title="2013 Scion FR-S Arrival">
            <img src="http://i2.squidoocdn.com/resize/squidoo_images/-1/lens10584771_1271704447MARIO_thumbnail.jpg" itemprop="image" title="2013 Scion FR-S Arrival" alt="2013 Scion FR-S Arrival" />
            <span>2013 Scion FR-S Arrival</span>
        </a>
    </li>
    <?php
}
?>

Another benefit is that the template can be changed as an individual file. So, if designs change, you never have to bother the back-end developers, unless new data is necessary for the items retrieved, but that’s a data issue, not a design issue.

Updates to the other files:

The call is being made from here

1
2
3
<a href="javascript:void(0);" class="jsonCall" data-template='#content-list-item' data-container='#my-container' data-qty='16' data-action='getmario'>Click Me!</a>

<div id="my-container"></div>

The JavaScript updated file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    $('.jsonCall').on('click',function() {
        var template = $(this).attr('data-template');
        var container = $(this).attr('data-container');
        var action = $(this).attr('data-action');
        var qty = $(this).attr('data-qty');
       
        $.ajax({
            url: '/ajax/main.php',
            type: 'post',
            data: 'qty='+qty+'&action='+action,
            dataType: 'JSON',
            success: function(data) {
                $(container).html('');
                var templateCode = $(template).html();
                for (var itemCount = 0; itemCount < qty; itemCount++) {
                    templateCode = templateCode.replace(/\[\[url\]\]/gi, data[itemCount].url);
                    templateCode = templateCode.replace(/\[\[thumb\]\]/gi, data[itemCount].thumb);
                    templateCode = templateCode.replace(/\[\[text\]\]/gi, data[itemCount].text);
                    $(container).append(templateCode);
                }
            }
        });
    });

The ajax called JSON returning php file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
// a sort of a controller to get the right function to run
if (isset($_REQUEST['action'])) {
    switch ($_REQUEST['action']) {
        case 'getmario':
            getMario();
            break;
    }
}

function getMario() {
    // normally would make a database connection to populate the data,
    // but that's not what we're testing here.
    // We only made one connection per call anyway.
    $qty = $_POST['qty'];
    $retVal = array();

    for ($itemCount = 0; $itemCount < $qty; $itemCount++) {
        array_push ($retVal, array(
            'url' => 'http://www.motortrend.com/roadtests/oneyear/coupe/1302_2013_scion_fr_s_arrival/',
            'thumb' => 'http://i2.squidoocdn.com/resize/squidoo_images/-1/lens10584771_1271704447MARIO_thumbnail.jpg',
            'text' => '2013 Scion FR-S Arrival'
        ));
    }
    $retValJSON = json_encode($retVal);
    echo $retValJSON;
}

?>

Just to show once again that the more complex your html will be, the more data you are returning the old way, whereas the new way, you are barely adding anything at all to the data coming back. In the long run, you will benefit significantly from the template way of doing things.

Changed the oldway file:

1
2
3
4
5
6
7
8
// from
...
<li itemprop="stuff">
...
// to
...
<li itemprop="stuff" id="item_<?php echo $itemCount; ?>">
...

Changed the template file:

1
2
3
4
5
6
7
8
9
10
11
12
// from
...
<li itemprop="stuff">
...
// to
...
<li itemprop="stuff" id="item_[[id]]">
...
// and added this line to our array of data
...
'id' => $itemCount,
...

Minor changes, HUGE difference. The new results are in, and the new way has gone up to 268 bytes, while the old ways have gone up to 353 bytes. Now we’re at 31.7% increase which goes to show you that we went from just under 30% difference to 31.7% (almost a 2% increase in bandwidth, just from a single change). This might be nothing when considering the small size of data, but for multi million user websites this number can be real significant. And it separates your code better.

Yes, you will use up more space initially when loading the templates. About 115 bytes more, but in the long run, there are greater benefits.

It’s-a me, Mario!

Since I absolutely love the Super Mario Brothers, I couldn’t bare the thought of not upgrading an old classic to the power of HTML5. Am I saying that I’ll re-create the entire game here? No… probably not. But, it’s nice to know that with today’s technology, you can come pretty darn close, and sometimes, even surprise yourself.

Taken from the basic Mario where I had a jumping block on a white background, I think you’ll find it refreshing to see Mario re-evolve in the web world, and have this game be playable on any device eventually. That’s my goal.