Archive

Archive for the ‘JavaScript’ Category

CrossSlide JQuery Plugin Test

March 21st, 2009 4 comments

CrossSlide is a neat plugin for JQuery that allows you to fade in from one image to the next, and even using some cool visual effects like panning. So I thought I would see how hard it is to set up and what sort of limitations is has (if any).

Simple Fading

The simple fading is nice and easy and can be accomplished with just a few lines of code and a div tag.

<script type="text/javascript">
  //<!--
  $(function(){
    $('#crossslide').crossSlide({
     sleep: 2,
     fade: 1
    }, [
     { src: 'google.png' },
     { src: 'talkincode.png' },
     { src: 'php.png' }
    ]);
  });
  // -->
</script>

This uses the following div tag as a place holder to display the images.

<div id="crossslide" style="width:500px;height:500px;"></div>

Here is an example of the script in action.

If you want to add a link to each image, so that the user can click on the current image and be taken to a page, then you can use the href attribute of the image.

<script type="text/javascript">
  //<!--
  $(function(){
    $('#crossslide').crossSlide({
     sleep: 2,
     fade: 1,
     shuffle: true
    }, [
     { src: 'google.png',
      href:'http://www.google.com/' },
     { src: 'talkincode.png',
      href:'http://www.talkincode.com/' },
     { src: 'php.png',
      href:'http://www.php.net/' },
    ]);
  });
  // -->
</script>

I have also included the shuffle parameter here, which can be used to randomise the order of the images.

Here is an example of the same script as above, but with the addition of the href attribute.

Fancy Fading

A different effect of fading can be achieved by using the speed option (instead of the sleep option) and using a dir attribute for each image. Speed is an option that sets how fast an image will scroll across the area. The direction of the scroll can be controlled through the dir attribute.

Use the following code to create this effect.

$(function(){
 $('#crossslide').crossSlide({
  speed: 45,
  fade: 1
 }, [
  { src: 'google.png', dir:'up' },
  { src: 'talkincode.png', dir:'down' },
  { src: 'php.png', dir:'left' }
]);
});

Be careful here, if the div is even 1 pixel bigger than your image then you will have a funny error that states:

uncaught exception: crossSlide: picture number 1 is too short for the desired fade duration.

Took me a minute or two to track down but it makes sense because the JavaScript is trying to create an animation that moves the image past the div in the style of a window. If the div is larger than the image then this effect can’t be created and so it fails. Because my images are 500×300 pixels I have created a div that is 100 pixels smaller on each side.

<div id="crossslide" style="width:400px;height:200px;">Loading...</div>

Here is an example of the fancy fading script in action.

The href attribute still works with this style so you can include it if you want to.

Ken Burns Fading

The Ken Burns effect is basically a panning and zooming effect, and is a nice effect for a still image. It is the most complicated of the three effect styles to implement, but this is just due to the number of options it takes.

This effect differs from the other effects as you need to include it in inside a DOM-ready handler.

jQuery(function($) {
});

Each image must have a src, from, to and time attribute. The src attribute is the same as before and is just a reference to the image. The to and from attributes follow the same syntax as the background position CSS rule, but with the addition of a third parameter which controls the zooming. The time attribute is used to control how long the panning and zooming will take.

So, to pan from top right to bottom left in 2 seconds you would use the following:

src: 'talkincode.png',
from: 'top right',
to: 'bottom left',
time: 2

To zoom in at the same time you simply include the third parameter. A value of 1.0x is the same size as the original image so the following code makes the image bigger whilst panning.

src: 'talkincode.png',
from: 'top right' 1.0x,
to: 'bottom left' 1.5x,
time: 2

The href attribute can also be used with this fade style. Here is code code that uses different effects across three images.

jQuery(function($) {
 $('#crossslide').crossSlide({
  fade: 1
 }, [
  {
   src: 'google.png',
   href: 'http://www.google.com/',
   from: '50% 100% 1x',
   to: '50% 0% 5.7x',
   time: 3
  }, {
   src: 'talkincode.png',
   href: 'http://www.talkincode.com/',
   from: 'top left',
   to: 'bottom right',
   time: 2
  }, {
   src: 'php.png',
   href: 'http://www.php.net/',
   from: '100% 80% 1.9x',
   to: '80% 0% 1.1x',
  time: 2
  }
 ]);
});

Here is an example of the Ken Burns Effect script in action.

Conclusion

This is a very nice effect plugin that is quite easy to implement and runs very well (at least on the browsers I’ve tested it on). Using this plugin allows you to move away from using flash to do the same thing. It is nice that you can enclose it into any element, rather than be forced to use an image tag.

The only thing I would say that needs improvement is that the plugin should trigger some callback events (like onchange) so that it can be tied into an application. At the moment it can only be used as a neat little effect on a page, but I can see lots of potential for it. Also, if you any images are missing from the list the plugin simply does nothing. If the image isn’t there then the plugin should skip over it.

JCrop Extension Implementation In PHP

March 18th, 2009 2 comments

I came across a really nice looking plugin for JQuery the other day that allowed you to select part of an image. This plugin is called JCrop.

This plugin supports things like thumbnail generation, animation, styling and event handling. The only problem is that this is all done on the client side, there is one example of a PHP script that resizes images using PHP, but this only works with JPEG images. The site says that improvements to the code are left as an exercise to the reader, so I though I would take a shot at it.

Rather than start from scratch with the PHP implementation I have adapted the ImageResize class that I talked about some months ago. I have changed the name to ImageManipulation as it has gone beyond a simple image resizing class.

I won’t post the entire source code of that class here as it will take up too much space, instead I will provide a link to it.

Talk In Code ImageManipulation class.

I’m going to be using the same JavaScript code from the Jcrop website example, but for convenience I will reproduce it here with some small changes. Basically I have removed all unnecessary HTML, included a DOCTYPE declaration, cleaned up the script tags and used the JQuery library from the Google AJAX Libraries site.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
  <script src="jquery.Jcrop.pack.js" type="text/javascript"></script>
  <link rel="stylesheet" href="jquery.Jcrop.css" type="text/css" />
 
    <script type="text/javascript">
    //<!--
 
      $(function(){
        $('#cropbox').Jcrop({
          aspectRatio: 1,
          onSelect: updateCoords
        });
      });
 
      function updateCoords(c)
      {
        $('#x').val(c.x);
        $('#y').val(c.y);
        $('#w').val(c.w);
        $('#h').val(c.h);
      };
 
      function checkCoords()
      {
        if (parseInt($('#x').val())) return true;
        alert('Please select a crop region then press submit.');
        return false;
      };
    // -->
    </script>
  </head>
  <body>
 
    <h1>Jcrop - Crop Behavior</h1>
    <!-- This is the image we're attaching Jcrop to -->
    <img src="flowers.jpg" id="cropbox" />
 
    <!-- This is the form that our event handler fills -->
    <form action="crop.php" method="post" onsubmit="return checkCoords();">
      <input type="hidden" id="x" name="x" />
      <input type="hidden" id="y" name="y" />
      <input type="hidden" id="w" name="w" />
      <input type="hidden" id="h" name="h" />
      <input type="submit" value="Crop Image" />
    </form>
  </body>
</html>

This also includes the JCrop file (jquery.Jcrop.pack.js) and a CSS file (called jquery.Jcrop.css) that will make the selection box on the image look nice.

The function updateCoords() is used by JCrop to enter the coordinates of our crop into a set of hidden input boxes. This allows us to use a POST request to send the coordinates to our server. This is a callback function set in the JCrop initialization.

The aspectRatio setting forces the cropping box created to be square.

The checkCoords() function simply checks to see if a crop window has been created. If not then an alert is raised and the browser does nothing.

Next we need to implement our PHP code that will capture the image parameters and crop our image to a given size. This is done by creating an instance of the ImageManipulation class (giving the filename as the source), running the setCrop() method, with the correct parameters and using the show() method to display the output to screen.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
 $src = 'flowers.jpg';
 
 require('ImageManipulation.php');
 
 $objImage = new ImageManipulation($src);
 if ( $objImage->imageok ) {
  $objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']);
  $objImage->resize(500);
  $objImage->show();
  //$objImage->save('12345.png');
 } else {
  echo 'Error!';
 }
 exit;
}
?>

This will display the output to screen only, if you want to save the output to a file then remove the comment on the line that runs the save() method.

I have put an example of this JCrop implementation in action in the same place as the ImageManipulation class. I have also created a source file so that you can download the full thing easily.

This method of cropping will work with any file type.

Something To Be Aware Of JavaScript isNaN

March 17th, 2009 1 comment

The isNaN() function (NaN stands for Not a Number) can be useful if you are looking at form inputs or similar and is used to detect if a value is not a number. For example, the following code shows the output of isNaN() on two variables.

var number42 = "42";
var wibble = "wibble";
alert(isNaN(number42)); // Prints out false
alert(isNaN(wibble)); // Prints out true

This first test is true because the number 42 is, in fact, a number. The second test is false because wibble isn’t a number. This is simple enough, but what if we started looking at some different values?

var empty = "";
var nothing = null;
alert(isNaN(empty)); // Prints out false
alert(isNaN(nothing)); // prints out false

What is happening here is that isNaN() tries to converts any value it is given into an number, which means that "" and null get converted to 0 and the function returns false because they are now numbers. You can try this out yourself by doing one of the following:

var empty = "";
alert(+empty); // Prints out 0
alert(Number(empty)); // Prints out 0

To solve this problem you can use the parseInt() function. This takes a string as an input and tries to convert it into a number, if this is not possible then it returns NaN. If parseInt() is given an empty string or a null value it will also return NaN, rather than converting them to 0. This gives us a mechanism by which we can test values using a combination of parseInt() and isNaN().

var empty = "";
alert(isNaN(parseInt(empty))); // Prints out true

Finally, if we give isNaN() and parseInt() an undefined value the results are as follows.

var nothing;
alert(parseInt(nothing) + ", " + isNaN(nothing)); // Prints out NaN, true

The isNaN() function returns true because it can’t convert the value into any number.

var nothing;
alert(+nothing);
alert(Number(nothing));

This code prints out NaN for both of the alert statements.

Google Ajax Libraries

March 13th, 2009 No comments

Strictly speaking the Google Ajax libraries don’t contain only Ajax libraries, but they are very useful for a variety of reasons. Google host a variety of different JavaScript libraries which you can link to on your pages rather than download the library and host it on your server. You can use MooTools, JQuery, Prototype/Scriptaculous, Dojo and even the Yahoo! User Interface Library.

How To Use Them

Using the Google Ajax libraries on your own site is quite easy, and you can do it in a number of different ways.

Normally, you would download the latest and greatest version of your chosen library and upload it to your site. Here is an example using the MooTools.

<script type='text/javascript' src='http://www.talkincode.com/'></script>

You can include this via Google using the following.

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/mootools/1.2.1/mootools-yui-compressed.js'></script>

If you are working on a development server you can also include the uncompressed version so that you can see where any errors are coming from.

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/mootools/1.2.1/mootools.js'></script>

If you want to download version 1.11 instead of version 1.2.1 by changing the folder:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/mootools/1.11/mootools.js'></script>

You can also use the google.load() function to include the library you want with a single function call.

<script src="http://www.google.com/jsapi"></script>
<script>
  google.load("mootools", "1.2.1");
</script>

Ease Of Use

You have to admit that this method of including JavaScript is much easier than downloading the library manually, uploading it and then sorting the script tags out.

Quick Downloads

The first benefit of using this service is that users will not have to wait very long in order to download the JavaScript libraries that your site relies on to work. This is because they are downloading it from Google and not your site.

Concurrent Connections

Your browser can only open a certain number of connections to a domain; this is partly due to how browsers work but also due to how servers work. If you host your JavaScript libraries with Google then your browser will be able to run off and get them whilst it is downloading your page making the page load a little faster.

Better Caching

Rather than repeatedly downloading files from a site over and over again a browser will try to minimise this by only downloading what it hasn’t downloaded already. This is fine if you spend all of your time on a single site, but most people don’t and they will therefore download the same version of the same JavaScript library over and over again. This happens even if the server has aggressive caching turned on. By hosting your libraries with Google you basically allow a user who has visited a site using the same library as you to reuse the file they downloaded there on your site.

Don’t Use On Your Intranet

There is one small issue if you are using this sort of thing on an Intranet system in that it will create unnecessary network traffic from your network. This method can also leave Intranet systems utterly useless if your Internet connection goes down for whatever reason. Holding your JavaScript libraries locally will mean that your systems can continue to work, even if you are cut off from the outside world.

Word Of Warning

Some countries actively block connections to some sites; especially Google. So if you do include JavaScript libraries like this then the chances are that someone in Iran or China will certainly not be able to view any JavaScript components and might even get a load of authentication errors.

More Information

For more information on the different libraries available take a look at the Google Ajax Libraries page.

JS Bin

March 12th, 2009 No comments

JS Bin is an online tool that allows you to test JavaScript without having to muck about with files. You can just quickly cut and paste some code in and view the output. It is even possible to make the code you are looking at public and then use this as part of an ajax call in another instance of the application.

To get you started there is a nice help section, which also includes a couple of videos.

JS Bin

This tool really impressed me, especially the easy inclusion of several different JavaScript frameworks. I don’t mind testing JavaScript, but sometimes I just want to run a little bit of code on it’s own to see why it isn’t working as I expected it would. This tool fills that much needed gap, and the addition of allowing other people to view your code is a very nice feature. Well worth a look!