The Focus and The Pocus

March 30th, 2006. Tagged: JavaScript, News/personal

About tfatp.com

The Focus and The Pocus (a.k.a. tfatp.com) is a toy project of mine, started a couple of days ago in a moment when I had so much work on my plate, that the only way to stay relatively sane was to take a break, doing something different ;). So it goes.

User guide / feature list

  • Go to the site, move your mouse around and admire how colors are changing.
  • Click a square to "freeze" a color. Click again to un-freeze.
  • Point you mouse to the upper right corner to see the color definitions and a link to this page.

If you freeze a nice color combination, fell free to mail me a screenshot, I'd appreciate it.

OK, why? / History

Sometimes when I think about something (or just convincingly look as if I am), I find myself staring blindly into my monitor and clicking here and there. A usual place for this activity (due to the lack of a more appropriate word, let's say we'll call it activity) is the desktop where I single-click icons and watch them getting highlighted. Another fave is any average phpMyAdmin table, where colors change as you hover over a row and change again when you click.

In one such occasion a few days ago, that tfatp idea came to me and I thought it would be a nice CSS/JS exercise. So it goes.

The name is kind of influenced by Vonnegut's Hocus-Pocus, I'm currently re-reading some of the Vonnegut's books for the n-th time. How Hocus-Pocus became tfatp - well, if you've tried registering a domain name recently, you know it ain't so easy to get what you want. (But, as the old Stones' song goes, sometimes you might just get what you need 🙂 )

In case you're wondering, "so it goes" is an often-repeating phrase from Slaughterhouse-5. So it goes.

Todos

  • You might not notice it, but every time you click to freeze a color, it's saved to a database. So a to-do is to produce a report, once there is enough data, of which colors are considered freeze-worthy by people that come to the site. Maybe it can be useful the next time you design a site and you're lacking color ideas.
  • More interesting reports such as color of the day, of the week, by location... (Thanks, Brian!)
  • "Your color combination on your blog" sort of thing
  • Static URLs. If you freeze one or several nice colors, you should be able to get a static URL to send friends and family and they could reproduce the same thing.

If you think of a nice new feature - let me know.

Coding

In terms of coding it's all best practices. No, I mean, seriously. Well, front-end best practices at least. On the backend it's not the case, because the backend is just a few lines of PHP code.

Best practices, because there is a clean separation between:

  • content (a.k.a. markup or HTML),
  • visualization (a.k.a. styles, formatting or CSS), and
  • behaviour (JavaScript).

This means no font tags, no tables, no style attributes, no onclick-s or onmouseover-s. Needless to say it's XHTML-strict compliant.

Implementation

HTML

Nothing interesting here, just 4 divs placed in a container. That may explain why the markup is so beautiful and XHTML-strict. It would be actually harder to make it non-standards compliant 😉 Check the source out.

CSS

Here's the stylesheet. I'm using float to move the squares to the left and to the right and position: absolute to make setting the positioning and the heights possible. For example the fourth square (bottom right) has top: 50% and left: 50%

Behaviour - events

I'm using Yahoo! UI library scripts to attach events to different elements on the page. (Check my previous post for more Yahoo! UI). So I attach a mouseover listener to the container div. It's lazier than attaching 4 listeners to the 4 squares. Then I check the event to see what was clicked. If a square was clicked, I call a method to change its background.

BTW, all JS code is in behaviour.js

Similarly I attach a click event to the container div to do the freezing.

And two more listeners to handle mouseover/mouseout on the little "About" div.

JSON

Using the JavaScript Object Notation, I'm defining a variable focuspocus which is a class instance that contains all methods and properties I need, thus keeping the global namespace clean of any functions.

Colors

Generating random colors is easy, just use Math.random() to generate a random red value, a random green and a random blue. Use them to set the background by using the rgb(r, g, b) form.

Then getting the color value back is the tricky part (as I'm writing this I just thought I could simply store it once it's generated, duh!). So I'm using my little RGBColor library (described here) in its lightweight version (also used here) to parse the value returned by getComputedStyle() a.k.a. currentStyle in IE.

AJAX

I just couldn't launch anything without using AJAX, could I? So once you click to freeze a color, there is a tiny AJAX request to send the color you've just frozen and the square where you clicked. The aim is to store those and at some point try to make a noble use of them.

To make the AJAX request, I'm using the Yahoo!s UI connection lib.

YAHOO.util.Connect.asyncRequest(
    'POST',
    'frozo.php',
    {success: function(){}}, // callback
    'color=' + thecolor + '&sq=' + theid
);

Easy, isn't it? There is no response from the AJAX request and none is actually needed. So the success callback is an empty function. Just POST-ing two variables to frozo.php

Server-side

"Server side" is too big a name for the few lines in frozo.php. There is just DB connection and an INSERT. The interesting thing is that there's no DB abstraction, config, none of that. Just the good old mysql_query() call, which (don't tell anyone, but) I actually had to lookup on php.net, since I've used abstraction layers for years now and I've kinda forgotten... So it goes.

<?php
// error reporting - none in production
error_reporting(E_NONE);
// sanity check
if (empty($_POST['color']) || empty($_POST['sq'])) {
    die();
}
// session init
session_start();
// db connection
$db = mysql_connect('host', 'username', 'pass');
mysql_select_db('database', $db);
 
// insert
$sql = sprintf(
    'INSERT INTO frozo VALUES("","%d","%s","%s","%s",UNIX_TIMESTAMP())',
    intval(str_replace('sq','',$_POST['sq'])),
    mysql_real_escape_string($_POST['color']),
    mysql_real_escape_string(session_id()),
    mysql_real_escape_string($_SERVER['REMOTE_ADDR'])
);
$result = mysql_query($sql);
?>

Thanks for reading!

And have fun - tfatp.com. Hope you enjoy it. I surely enjoyed coding it 😉

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov