Archive

Posts Tagged ‘JQuery’

JQuery Timepicker Plugin

April 12th, 2009 1 comment

I had the need to create a time selecting component for a form, but I didn’t want to have lots of extra components. After a little bit of searching about I found the following JQuery UI plugin called timepicker.

This plugin will take a input box as the argument and will add three selection boxes for hours, minutes and seconds. It will then hide the original input box.

However, there were two thing that I needed that this plugin didn’t do. The first is that it was in a 12 hour format and the second is that the plugin didn’t have a second selection. So I decided to adapt that plugin in order to incorporate these things.

Here is the modified plugin.

(function($){
    jQuery.fn.timepicker = function(){
        this.each(function(){
            // get the ID and value of the current element
            var i = this.id;
            var v = $(this).val();
 
            // the options we need to generate
            var hrs = new Array('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23');
            var mins = new Array('00','05','10','15','20','25','30','35','40','45','50','55');
            var secs = new Array('00','05','10','15','20','25','30','35','40','45','50','55');
 
            // default to the current time
            var d = new Date;
            var h = d.getHours();
            var m = d.getMinutes();
            var s = d.getSeconds();
            
            // override with current values if applicable
            // round the minutes and seconds to nearest 10
            if(v.length == 8){
                h = parseInt(v.substr(0,2));
                x = parseInt(v.substr(3,2));
                m = (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
                x = parseInt(v.substr(6,2));
                s = (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;                
            }
    
            // build the new DOM objects
            var output = '';
            
            output += '<select id="h_' + i + '" class="h timepicker">';                
            for(hr in hrs){
                output += '<option value="' + hrs[hr] + '"';
                if(parseInt(hrs[hr]) == h) output += ' selected';
                output += '>' + hrs[hr] + '</option>';
            }
            output += '</select>';
    
            output += '<select id="m_' + i + '" class="m timepicker">';                
            for(mn in mins){
                output += '<option value="' + mins[mn] + '"';
                if(parseInt(mins[mn]) == m) output += ' selected';
                output += '>' + mins[mn] + '</option>';
            }
            output += '</select>';                
    
            output += '<select id="s_' + i + '" class="p timepicker">';                
            for(ss in secs){
                output += '<option value="' + secs[ss] + '"';
                if(secs[ss] == s) output += ' selected';
                output += '>' + secs[ss] + '</option>';
            }
            output += '</select>';                
    
            // hide original input and append new replacement inputs
            $(this).css('display','none');
            $(this).after(output);
        });
        
        $('select.timepicker').change(function(){
            var i = this.id.substr(2);
            var h = $('#h_' + i).val();
            var m = $('#m_' + i).val();
            var s = $('#s_' + i).val();
            var v = h + ':' + m + ':' + s;
            $('#' + i).val(v);
        });
        
        return this;
    };
})(jQuery);

You can view and download this code here.

The plugin will also update itself with the time that is present in the text field, as long as it matches the format HH:MM:SS.

I have also setup a test page for this timeplugin.

You can run the plugin by using the following code:

$('#timepicker').timepicker();

Display JavaScript Source Programatically

March 23rd, 2009 2 comments

If you are running a JavaScript example page you can use the following function that will take the last script element on the page and print it out in a code tag. It uses JQuery to do the work, so you will need to include that library before using this function.

<script type="text/javascript">//<![CDATA[
 function displaySource(name) {
  $('<code>'
   + $('#display-' + name).prevAll('script').eq(0).html()
   .replace(/^\s*|\s*$/g, '')
   .split('\n').slice(1, -1).join('\n')
   .replace(/(^|\n) /g, '$1')
   .replace(/('[^']*')/g, '<em>$1</em>')
  + '</code>')
  .insertAfter('#display-' + name);
 }
//]]></script>

The function works by selecting the current script tag and finding all script elements before it. It then selects the first one it finds and outputs the contents to a code tag. It uses a few regular expressions to convert some of the characters to a more human readable format. The function is called like this.

<script type="text/javascript" id="display-test">displaySource("test");</script>

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.

Adding A Sortable List To WordPress

February 19th, 2009 No comments

A sortable list is simply a list of items that can be dragged and dropped to alter the order of those elements.

There are two sortable lists available in WordPress, one from the JQuery framework and one from the Scriptaculous framework. For a sortable list you will need a list, so here is a simple one.

<ul id="sortcontainer">
<li class="sortable">Item 1</li>
<li class="sortable">Item 2</li>
<li class="sortable">Item 3</li>
<li class="sortable">Item 4</li>
</ul>

JQuery Sortable

The JQuery sortable control is actually a plugin and not part of the standard JQuery framework. The first thing we need to do is add in the correct JavaScript libraries that we need to use. We do this with the wp_enqueue_script() WordPress function. The are quite a few different things that are needed so you can use an array to pass in all of the options.

wp_enqueue_script( array("jquery", "jquery-ui-core", "interface", "jquery-ui-sortable", "wp-lists", "jquery-ui-sortable") );

Here is the JavaScript code that is needed to create the sortable list.

<script type="text/javascript">
 jQuery(function($) {
 
 var smpSortable;
 var smpSortableInit = function() {
  try { // a hack to make sortables work in jQuery 1.2+ and IE7
   $('#sortcontainer').SortableDestroy();
  } catch(e) {}
  smpSortable = $('#sortcontainer').Sortable( {
  accept: 'sortable',
  onStop: smpSortableInit
  } );
 }
 
 // initialize sortable
 smpSortableInit();
});
</script>

For more information on the sort of options available have a look at the JQuery Sortables documentation.

Scriptaculous Sortable

To use the Scriptaculous sortable list we add in the scriptaculous-dragdrop library using the wp_enqueue_script() WordPress function.

wp_enqueue_script("scriptaculous-dragdrop");

Here is the code you need to create the sortable list, you need to include this on the page below the list.

<script type="text/javascript">
  Position.includeScrollOffsets = true;
  Sortable.create('sortcontainer',{
   tag: 'li',
   scroll: window
  });
</script>

For more information on the sort of options available have a look at the Scriptaculous Sortables documentation.

If you only want to run the wp_enqueue_script() function in the admin section of WordPress you can use the is_admin() function. This returns true if the code is run in the admin section, and false if run on the front end. Using this function you can stop JavaScript libraries being included when you don’t use them.