15 April 2008 - 22:42[How to] round corners on images with JavaScript

Something I’ve come to love about the JQuery JavaScript library is that, no matter what client-side scripting challenges arise these days, my first thought is “I bet there’s an easy way to do this with JQuery!”. I recently worked on a website where the client wanted rounded corners on a lot of the site’s elements, including images. A quick Google search found this jquery.corner plugin; which was, as most JQuery plugins are, extremely simple to implement and adapt for my own project.

The corner plugin has a bunch of ways to add corner effects to div elements, but unfortunately you can’t apply it directly to an image. Back to Google, I found a way to make it work with images: wrap it in a div and apply the corner code to the div element. This is good, but not best for our purposes. We still have to apply styles to make the divs match the size of their child image elements.

Objective:
To loop through all divs of a certain class, and automatically resize them to match their child image elements.

We’ll put this code inside our $(document).ready(function(){ … }) block so it runs as soon as the document is ready to run code.

We want to apply this code to all divs of a certain class, we’ll say class=”round-corners” in this example. To loop through every div of this class and run code on it, we use the wonderful JQuery.each function.

First, select images with a parent div element of this class (“round-corners”):
$(‘div.round-corners > img’)
and run the JQuery.each function to loop through:
$(‘div.round-corners > img’).each(function(id){ … })

Within this loop we want to select the image, and set the height and width of its parent div element. An easy way to do this is with the .height and .width functions. These functions are both accessors and modifiers, as is the case with many functions in JQuery.
Select the parent element of the selected image:
$(this).parent(‘div.round-corners’)
get the height of the image we’ve selected:
$(this).height()
so the whole line to set the height will look like this:
$(this).parent(‘div.round-corners’).height( $(this).height() );
Repeat for the width property with the .width function.

That should do it. Let’s take a look at the source for the whole page:

<script type="text/javascript" src="jquery.js"></script><script type="text/javascript" src="jquery.corner.js"></script><script type="text/javascript">$(document).ready(function(){ $('div.round-corners > img').each(function(id){     $(this).parent('div.round-corners').height( $(this).height() ).width( $(this).width() ); })$('.round-corners').corner();})</script><div class="round-corners"><img src="P3040004.JPG" alt="P3040004.JPG" /></div>

<div style="height: 130px; background-color: rgb(255, 0, 0);" class="round-corners">This is just a regular div with no image inside, but it will have round corners too!</div>

<div class="round-corners"><img src="bluehills.jpg" alt="bluehills.jpg" /></div>

An idea for improving this script would be to use the .wrap function to automatically wrap the images in divs

Have fun rounding corners, and please use them responsibly.

2 Comments | Tags: code, how to, web

24 February 2008 - 22:26[How to] use PHP to make form programming faster and easier

Programming forms is fairly easy, but it can certainly be one of the most tedious things to program. Anyone who’s programmed something like an application form with a decent amount of fields will tell you that it takes forever to make all of the form elements, and add the necessary code to pre-populate with values or pre-check radio buttons etc. (This is a good practice when programming forms, so a user doesn’t have to fill the form out again if it’s submitted with errors.) Whether you’re smart or just lazy, you’ll definitely want to make a simple PHP function to expedite this otherwise-boring process. Enter: the formElement() function.

/** * form elements */   function formElement($type, $name, $value = '',$extra = '')   {       global $_POST;       if ($type=='text') {           $val = (!empty($_POST[$name])) ? $_POST[$name] : $value ;           $o = '<input type="text" name="'.$name.'" value="'.$val.'"'.$extra.' />';       } elseif ($type=='radio') {           $checked = ($_POST[$name]==$value) ? 'checked="checked"' : '';           $o = '<input type="radio" name="'.$name.'" value="'.$value.'" '.$checked.' '.$extra.' />';       } elseif ($type=='checkbox') {           $checked = ($_POST[$name]==$value) ? 'checked="checked"' : '';           $o = '<input type="checkbox" name="'.$name.'" value="'.$value.'" '.$checked.' '.$extra.' />';       }

       return $o;   }

It’s pretty straight-forward, but I’ll break it down parameter-by-parameter.

$type – in my example, this is the same as the type attribute in the html input tag. You could expand the function to include textareas too, or whatever you need.

$name – same as the name attribute.

$value – For checkbox and radio types, it uses this value to check against the item in the $_POST array, and adds checked=”checked” where appropriate. For text types, it pre-populates the textbox with this value if the form hasn’t been submitted yet.

$extra – I use this for any other attributes you may need to add to your form elements. Things such as CSS inline styles, event handlers like onclick, and id or class attributes could go here.

So with our new formElement function, this;

   <input type="radio" name="fav_food" value="pizza" <?=($_POST['fav_food'] == 'pizza') ? 'checked="checked"' : '';?> /> Pizza   <input type="radio" name="fav_food" value="souvlaki" <?=($_POST['fav_food'] == 'souvlaki') ? 'checked="checked"' : '';?> /> Souvlaki

becomes this:

   <?=formElement('radio','fav_food','pizza');?> Pizza   <?=formElement('radio','fav_food','souvlaki');?> Souvlaki

1 Comment | Tags: code, how to, web

2 November 2007 - 23:04[How to] calculate daylight savings dates with PHP

This Sunday is the “fall back” date for daylight savings, which is awesome. In North America, DST time changes are on the first Sunday of November, and the first Sunday of March. On rare occasions, you might find a need for a PHP function that returns the first Sunday of a November, or the third Friday of January, or the X-th Y-day of Z.

First, let’s make a function to calculate the DST “fall back” date. Some quick planning:

  • The function will have a single, optional parameter for the year. (Default will be the current year).
  • We’ll loop through the days of the month until we get to the day we want, and return it as a UNIX timestamp.

Begin by defining our function:

function dstFallBack($year = '')

and handle the $year if none is supplied with a ternary operation:

$year = (empty($year)) ? date("Y") : $year ;

loop through the days until we get to the first Sunday (guaranteed to happen within 7 days). A simple for loop will do.

for ($x = 1; $x <= 7; $x++)

get the UNIX timestamp for the day of our iteration (November $x, $year). To do this we use the mktime function.

$date = mktime(0,0,0,11,$x,$year);

Check if the day is a Sunday using the date function. (I used "D" instead of "N" because "D" will work in older versions of PHP.

if (date("D", $date) == 'Sun')

If it's Sunday, then we're done, and we can return the $date

break; // no need to keep looping.

Here's the whole thing:

/*** Gets the date of the DST November "fallback"* In other words, the first Sunday in November** @param int $year* @return int*/function dstFallBack($year = ''){ $year = (empty($year)) ? date("Y") : $year ;

 for ($x = 1; $x <= 7; $x++)  {        $date = mktime(0,0,0,11,$x,$year);            if (date("D", $date) == 'Sun') {                $sunday = $date;                break;            }        }        return $sunday; }

Run it a few times as a test:

echo date("M jS, Y",dstFallBack()) . "\n";     // for 2007: 4-Nov-2007echo date("M jS, Y",dstFallBack(2009)) . "\n"; // 1-Nov-2009echo date("M jS, Y",dstFallBack(2016)) . "\n"; // 6-Nov-2016

The "spring forward" date is on the 2nd Sunday of a month, but the function is only slightly more complicated. Just for fun, we can put together a more reusable function (recall "X-th Y-day of Z").
To do this, just add a sort of flag as we iterate through days, like $Ydays_encountered, and increment it with each iteration.

/** * Get the Xth Y-Day of Month * "Abstract" as a double-entendre... * * @param int $xth * @param int $yday * @param int $month * @param int $year * @return int */function xthYday($xth, $yday, $month, $year = ''){ $year = (empty($year)) ? date("Y") : $year ;

 //The Xth Y-day will come up within the first X weeks, //so limit the for loop to X * 7 days. $for_limit = ($xth * 7);

 for ($i = 1; $i <= $for_limit; $i++) {  $date = mktime(0,0,0,$month,$i,$year);  if (date("D", $date) == 'Sun') {   $ydays_encountered++;    if ($ydays_encountered == $xth) {     $xthYday = $date;     break;    }  } } return $xthYday;}

echo date("M jS, Y",xthYday(1,'Sun',11,2007)); // 4-Nov-2007. Seems to work!

Hopefully this will be useful for some kind of events calendar or something.

No Comments | Tags: code, how to

22 July 2007 - 3:54[How to] create a simple web template using PHP’s output buffer

The PHP output buffer is exactly what it sounds like: it allows us to capture output and, instead of printing it to the screen immediately, set it as a variable and deal with it later on. The “output” could include echoed lines and ordinary markup outside of php tags. For example: if you include a file, you can set all the variables and run all the functions inside it, but save the output and display it in different parts of your template, like the title, meta tags, content etc. In this tutorial, I’ll explain how to use the PHP output buffer to implement very simple template system for your website.

This guide assumes you’ve already got a nice-looking template with something like an empty div for your page content. I’m using /index.php as my template file, and i’ll pass it the same of the page to display as a GET variable.

The template index.php file should look a bit like this:

[/index.php]

<?php//get the page to display, or use home.php if nothing is passed.$page = (!empty($_REQUEST['page'])) ? $_REQUEST['page'] . '.php' : 'home.php' ; //turn on output bufferingob_start(); //get the contents of the file (/pages/home.php etc.).//do this outside of php tags because the file most likely has its own php tags, as well as ordinary html in it.eval('?> ' . file_get_contents($_SERVER['DOCUMENT_ROOT'] .'/pages/'.$page) . '<?php '); //return the contents of the output buffer, and set it as a variable.$page_content = ob_get_contents(); //turn off output buffering, and clear the output buffer so we can do it again just as easily.ob_end_clean(); ?><!DOCTYPE [...]<title><?=$page_title;?></title><meta name="description" content="<?=$meta_description;?>" /><meta name="keywords" content="<?=$meta_keywords;?>" />[...]<div id="page-content"> <?=$page_content;?></div>[...]

The variables $page_title , $meta_description , and $meta_keywords are defined in the page content file ‘/pages/whatever.php’.

A page content file would look like this:

[/pages/home.php]

<?php//define meta and title tags$page_title = 'This is the page title!';$meta_description = 'This is the meta description';$meta_keywords = 'meta keywords, hot dogs, rap music';?><h1>Welcome</h1><p>This is a test of my simple template system.</p><p>I sure hope it works!</p><p><?phpecho 'I can echo things this way too...';?></p>

Then we’d access this page with the uri /index.php?page=home and the script would start the output buffer, then get the contents of home.php and set the variables, but not echo anything until you tell it to. You can do this as many times as you want, if you wanted to include a menu from an external file as well, for example.

2 Comments | Tags: code, how to, web

20 May 2007 - 20:29Forum Youtube Linker makes youtube links more useful

I wrote a little script that generates bbcode for linking to Youtube videos. It was inspired by the way GTalk and Orkut take Youtube URLs and show a screenshot and description etc.

It spits out forum bbcode that’ll look like this:

Yoji Biomehanika clip @ Sensation Black 2004

Youtube thumbnailYoutube thumbnailYoutube thumbnail
Yoji drops a sick track @ sensation black 2004Dark By Design – Blackout (yoji biomehanika mix)
http://www.youtube.com/watch?v=YfIPt5Ai5P0

It was basically a way for me to teach myself regular expressions in php. A few of my friends have already found it useful, so give it a shot if you post on any bbcode-enabled forums.

You can also set up a bookmarklet and point it to javascript:(window.location = ‘http://portfolio.itas.ca/~mackenzied/uchoob.php?url=’+location.href);
or drag this into your bookmarks/toolbar: Link to this Youtube video

2 Comments | Tags: code, video, web