Toggle Functionality for Clean PHP

Requirements:
* jQuery
* Font Awesome
* AJAX capabilities
* .hidden = display: none;

So, I decided that just controlling the front end via the back end wasn’t enough. I debated for a long time and was reluctant to add new functionality to the ajax controller… then I realized that I’m using a lot more of this functionality, so, I caved in.

This complements the ajax functionality by adding a toggle feature for either items that toggle out (2 state on/off), or items that toggle other elements on or off; still 2 state.

The first thing I did was to add some classes to the elements that will perform the toggling. I added a wrapper around two elements (the togglers) and proceeded to play around with them.

1
2
3
4
<span class="trigger-wrapper" data-trigger="toggle">
    <a href="" class="tmbtn trigger hidden" data-action="test_toggle"><i class="fa fa-toggle-on"></i> Active</a>
    <a href="" class="tmbtn trigger" data-action="test_toggle"><i class="fa fa-toggle-off"></i> Inactive</a>
</span>

The trigger-wrapper class was added to wrap everything in one molecule.

I added the data-trigger attribute to the wrapper because this is what will determine what toggle type to perform… Is it a straight toggle of two items, show / hide an element, or both?

The trigger classes are what determines what triggers the toggle. These trigger elements will swap out their hidden classes. That’s how they toggle.

Here’s two more HTML examples of the content pieces:

1
2
3
4
5
6
<div class="trigger-wrapper reset" data-trigger="dropdown">
    <a href="" class="tmbtn trigger" data-action="test_toggle"><i class="fa fa-ellipsis-h"></i></a>
    <div class="target hidden init-hidden">
        [Content]
    </div>
</div>

… and…

1
2
3
4
5
6
7
<div class="trigger-wrapper reset" data-trigger="dropdown-toggle">
    <a href="" class="tmbtn trigger hidden init-hidden" data-action="test_toggle"><i class="fa fa-chevron-up"></i> Show Less </a>
    <a href="" class="tmbtn trigger" data-action="test_toggle"><i class="fa fa-chevron-down"></i> Show More </a>
    <div class="target hidden init-hidden">
        [Content]
    </div>
</div>

Notice how these last two items had the “init-hidden” class added, and the togglable content has “target” on it.

Now, for the JavaScript (jQuery) that drives the whole thing… (Assuming that .hidden already exists in your CSS as display: none).

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
...
var _toggle_type = '';
...
var $parent = $this.parent();
...
if (typeof($parent.attr('data-trigger')) !== 'undefined') {_toggle_type = $parent.attr('data-trigger');}
...
// In the ajax call of the JavaScript file (data is what comes back in the success function) ...
data._toggle_type = _toggle_type;
data.$parent = $parent;
postAjax(data);
...
// And of course, the switch case for the different toggles...
switch (data._toggle_type) {
    case "toggle":
        data.$parent.find('.trigger').toggleClass('hidden');
        break;
    case "dropdown":
        data.$parent.find('.target').toggleClass('hidden');
        break;
    case "dropdown-toggle":
        data.$parent.find('.trigger').toggleClass('hidden');
        data.$parent.find('.target').toggleClass('hidden');
        break;
}
...

So now, we have a lot of the functionality to handle our togglability.

This completes our addition to the Clean PHP code that I’ve been working on here: https://github.com/gbutiri/cleanphp

PHP Frameworks Suck

It’s kind of funny. After trying to understand Zend 2, I decided that I was happier with Core PHP. I noticed that anyone can pick up any framework and learn it in a few days, or even a few weeks, but to master it, you really need to spend a lot of time with it. I’ve spent 11+ years with PHP at the time of this writing. I know PHP.

Why have any framework? For most do it yourself type projects, just build a website from the ground up. You already have 4 great layers (Apache or server, MySQL or Database, PHP or backend language, and HTML, CSS, JS all in one). This looks like a LAMP stack to me. Why do I like keeping it this simple? Well, you don’t “need” anything else. Really. This is all you need to build anything. And I do mean, ANYTHING! You name your project, and i can build it.

My only caveat is jQuery. I’ve gotten used to it over the years, and in a way I wish I could go back to plain JS. I mean, for the most part, I still use JS, I just use jQuery for selectors / DOM manipulation, events, and the ever so simple to use ajax function. The main reason I use jQuery is because, otherwise, I would just write my own functions to do all these things. jQuery just makes sense to use.

My next task is to convert all my jQuery into JS at some point. Why? Because that’s what the browsers understand. The browsers don’t understand jQuery, or angular, or LESS or SASS on their own. They need pre-processors and libraries to convert all that.

This brings me to my other point. The backend should be no different. PHP is what is already installed on the server. Running PHP code in your files speaks directly to the PHP installation on Apache. You don’t need additional overhead to make things work better. Write PHP, done. You can structure your PHP in logical functions to make it work for you, such as getMeSomeData(), or renderThisHtmlBlock(). But that’s it. At its core, PHP is a great and most opened and powerful framework of all. Why add so many layers of abstraction on top of it?

My next good practice is to write MySQL directly into my php code. Why not? That’s the fastest processing you’re ever going to get without involving overhead. Use propell? Why? Just so you can stack php functions that eventually build out what you meant to say with MySQL anyway? Again, more layers of abstraction? What’s the point? Because it doesn’t “LOOK” like SQL? Is that really a valid excuse? Learn some damn MySQL like a good programmer, and remove all those PHP overhead functions to keep your site optimal.

It’s not what you use, it’s how you use it. Developers have become so lazy over the years, and no one cares about code itself. They treat it like they’re bored of it and just need to add layers of complexity.

The only thing that matters is how the client side performs. All of my projects’ pages load faster than 2 seconds, out of which most load under 1 second. In the end, that’s what matters. And, the turnaround time for most of my development is minutes, not days like most projects dependent on builds.

And I simply don’t want to discuss things like memcached, composer, ruby (for SASS), or any other dependency that’s simply not necessary. Are your websites fast? Then, that’s what matters. I worked at this one company where they would be concerned with micro optimizations such as to use array brackets instead of array_push function. At the same time, they were using propel that would run through dozens of php functions to get data, and their pages were loading in over 4 seconds, with unoptimized images, and over a hundred http requests. I just don’t understand this sort of mentality. These things should matter no matter if you are running an SEO site, or a private LAN intranet. Users will complain when your site loads in over 2 seconds. That’s a rule.

I’ve built many systems over and over and over only to come to the same conclusion. Simplicity just works better. Ask Steve Jobs.

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.