My first bit of Mootools and centering a Google Map in a hidden div

Save on DeliciousShare on Facebook+1Pin it on PinterestSubmit to redditSubmit to StumbleUponShare on TumblrShare on Twitter

Started a new job last week for a really cool agency in a place I really want to work* – but they are Mootools users not jQuery folk, so I am been thrown headlong into (among other things) the world of Mootools. I’m used to just sitting down and being able to make things work quickly and painlessly with jQuery and it is funny being back to basics again. Today I wrote my first useful bit of Mootools code, which in the grand scheme of things is nothing – just a nice fading toggle to show and hide a Google Map – but it still felt good.

Along the way I had to ran into a problem with my map – when I showed it the centre-ing was gone – I tried all sorts of things… map.checkResize() didn’t work and map.setCenter() didn’t work.

Eventually I deduced that first you actually need to call both functions – reset, then centre e.g.

 
    map.checkResize();
    map.setCenter(new GLatLng(51.90568, -1.33214));

Along my way I have found a great article comparing jQuery and Mootools – which I would recommend to anyone going either way.

*But it is a kind of a personal philosophy not to ever say on my blog where I do work, just because. I’ve taken over a big project running on a Cloud server written by a load of other people, the sort of thing that is hard but very rewarding.
** I have no idea where those coordinates are. Maybe Up North somewhere?

Minimum age with the jQuery UI Datepicker

Save on DeliciousShare on Facebook+1Pin it on PinterestSubmit to redditSubmit to StumbleUponShare on TumblrShare on Twitter

Minimum age with the jQuery UI Datepicker

Just been working on a registration form where the minimum age of registering users has to be 18. Using the fabulous jQuery UI Datepicker (see documentation it’s really easy to set up a Date of Birth field so that the a user has to be a least 18 years old.

1
2
3
4
5
6
7
8
9
10
11
12
13
 
$(function() {
  $("#dob").datepicker(
    {
      minDate: new Date(1900,1-1,1), maxDate: '-18Y',
      dateFormat: 'dd/mm/yy',
      defaultDate: new Date(1970,1-1,1),
      changeMonth: true,
      changeYear: true,
      yearRange: '-110:-18'
    }
  );					
});

jQuery plugin to print HTML forms

Save on DeliciousShare on Facebook+1Pin it on PinterestSubmit to redditSubmit to StumbleUponShare on TumblrShare on Twitter

Recently for a project, a client wanted to be able to print pages from a web application that were just forms. This was never intended when the application was originally built, so there were no separate view screens of data. Naively I thought this would be easy – knock up a print style sheet and bob’s your uncle… if only.

There are a couple of problems that just aren’t really fixable using a pure CSS solution, firstly <select> menus look pretty horrible no matter what you to them and <textarea> fields look fairly bad, but even worse than their aesthetic merits (or lack of rather) is the fact that the overflowing content i.e. the content that you need to scroll to see, will not be printed.

In the end for the application I ended up adding views, but it got me thinking and so I’ve written a quick jQuery plugin to print forms. It works by looking for any <select> menus or <textarea> fields and replacing them with <div> tags styled to look like form elements. When you click on one of the <div>s to edit it, it reverts to the original form element and when it looses the focus (using the jQuery blur() method) the field is swapped back and replaced by the <div>.

When you come to print the form because all of the <select> menus and <textarea> fields have been replaced by <div>s you can style them as you want using a print style sheet and get a nice looking form with no missing content.

Have a look at the working example and view source to see how to use it.

download printform plugin example

You will want to edit / write CSS for both screen and print appropriate to your situation.
Tested on IE6, IE7, Firefox 2.0.

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
 
/*
 * printform 1.0
 * By John Elliott (http://www.flipflops.org)
 * Copyright (c) 2008 John Elliott
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
 
/**
 * convert textareas and select tags to divs so that you HTML forms can be printed.
 *
 *
 *
 * @name printform
 * @type jQuery
 * @author John Elliott (http://www.flipflops.org)
 * @desc 
 * 
 * @example $('#tester').printform();
 * @desc call the plugin on #tester - any select or textareas will be replaced
 *
 * @param settings - not used, but included for future proofing! (I'm sure there will be options sometime...)
 *
*/
 
jQuery.fn.printform = function(settings){
	return this.each(function(){
		new jQuery.printform(this, settings);
	});
}
 
 
 
jQuery.printform = function(obj, settings) {
 
  	/*
  	* within a parent object - replace the textareas and select menus
  	*/
 
 
 	init(obj, 'textarea');
	init(obj, 'select');	
 
 
	function init(obj, fieldType) {
 
	/*
	* loop through each instance of an element within the parent 
	*/
 
		obj = jQuery(obj).attr('id');
 
		jQuery('#' + obj + ' ' + fieldType).each( function() {
 
			var id = jQuery(this).attr('id');
 
			field_replacer(id, fieldType);
		});
	}		
 
 
	function field_replacer(id, fieldType) {
 
	/*
	* function to replace the elements with divs
	*/
 
			str = jQuery('#' + id).val();
			str = str.replace(/\n/g, '<br />');
 
			if ( jQuery('#replace-' + id).length > 0 ) {
				// if a replacement div already exists for this element, then just show it.
				// update the content of the replacer with the edited content
				jQuery('#replace-' + id).html(str).show();			
			} else {
				// otherwise create a new replacement div for the element
				jQuery('#' + id).after('<div class="' + fieldType + '-replace" id="replace-' + id + '">' + str + '</div>');			
			}
 
			jQuery('#' + id).hide(); // hide the element that has just been replaced
			field_watcher(id, fieldType); // add event listeners
	}											
 
	function field_watcher(id,  fieldType) {
 
	/*
	* add listeners to the elements
	* onclick - show the original element and hide the replacer
	* onblur - call the field_replacer to update the page
	*/
 
		jQuery('#replace-' + id).click(function() {
 
		jQuery('#' + id).show().focus();
		jQuery('#replace-' + id).hide();
 
		jQuery('#' + id).blur(function() {
 
			field_replacer(id,  fieldType);								
 
		});
	});
	}
};

Thanks to to Mike Alsup for his great (if rather daunting) guide to writing plugins on Learning jQuery.

jQuery – watch a checkbox field

Save on DeliciousShare on Facebook+1Pin it on PinterestSubmit to redditSubmit to StumbleUponShare on TumblrShare on Twitter

This is a simple function I wrote that will monitor a <checkbox> field on a form. If the <checkbox> is ticked then it will show a specified <div> and if the <checkbox> is un-ticked then it will hide the specified <div>.

View the working example

Initially I thought that I might be able to use the .toggle() function – but I when users returned to a form I needed the <div>s to show or hidden according to stored values.

I also have a very similar function that does the same thing for <select> fields. Logically you might then combine the functions into a single function or a plugin that could monitor checkboxes, radio buttons, select menus and show or hide <div>s accordingly – but at what point does the complexity of the just using the function outweigh the simplicity of using it? This is something I haven’t decide on yet.

At the moment I can just call it like so:

1
2
 
testCheckbox('id_of_checkbox', 'id_of_div');

If I were to combine these functions I would likely loose this speed / clarity – for instance a <select> might want to show or hide different <div>s based on different selected values and then I would need to start passing arrays to the function – loosing the initial simplicity. The only answer is to go ahead, write one and see what happens.

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
 
<script>
   $(document).ready(function(){
 
 
 
   testCheckbox('showHide', 'targetDiv');
 
 
 
 
   function testCheckbox(key, target){
 
    if($('#'+key).is(":checked")){
     $('#'+target).show();
    }
    else {
     $('#'+target).hide();
    }
 
    $('#'+key).click( 
 
 
 
      function()
       {
 
        if($('#'+key).is(":checked"))
         {
          $('#'+target).show();
         }
        else
         {
          $('#'+target).hide();
         }
       }
     );
 
 
   }
 
   });
</script>

Note When I wrote this function it seemed logical to use the .change() function – but I have had to chnage this to .click() because .change() seems to fail silently and unpredictably in IE7.

A simple jQuery menu with persistence using cookies

Save on DeliciousShare on Facebook+1Pin it on PinterestSubmit to redditSubmit to StumbleUponShare on TumblrShare on Twitter

Recently I’ve been making a concerted effort to learn jQuery the JavaScript framework as opposed to just using all the wonderful plugins off the shelf.

Recently I needed a bit of code to show and hide a navigation menu, but with persistence using cookies so as you move from page to page it can remember which sections to show. I was pretty confident, using bog standard JavaScript I knew I could knock it out really quickly, but The whole point of learning something new is to learn something new so I decided to do it using jQuery. I was pretty confident, last week I wrote some quite complex form validation code in a fraction of the time I could’ve done it in without using jQuery (it’s that pretty but it works well and it was my first attempt to do anything at all complex).

Getting the menu to work has been quite a struggle and I had to spend a surprising amount of time getting it to work, and judging by the posts on various blogs and groups a lot of other people have been stumped by this one too.

Anyway here is my solution, if anybody can help me simplify it further, their help would be greatly appreciated. Obviously you need to download jQuery, you will need to include the code and you will need an unordered list to act as the menu, in this example id=”#demo-menu”.

A couple of posts have been really invaluable figuring out how to do this, so credit where it’s due, thanks:

View the working example

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
$(document).ready(function() {
 
		$("#demo-menu > li > a").not(":first").find("+ ul").slideUp(1);
 
		$("#demo-menu > li > a > span").text('+'); // add an indicator to the menu items to show there is a child menu
 
		$("#demo-menu > li> a").each(function() {
			toggleMenu(this);
			checkCookie(this);
		});
 
 
 
		function checkCookie(id)
			{
				/*
 
						check if there is a cookie set for a sub menu 
						if there is then show the menu
 
				*/
 
				var cookieName = id.id;
 
				var c = readCookie(cookieName);
 
				if(c === 'show') {
 
					$(id).each(function() {
 
						$(this).children("span").text('-');
						$(this).find("+ ul").slideDown('fast');
 
					});
 
				}
			}
 
		function toggleMenu(id)
			{
				$(id).click(function() {
					/*
							toggle the +/- indicators
					*/
					togglePlusMinus(this);	
 
					/*
						toggle the menu open or closed
					*/
					$(this).find("+ ul").slideToggle("fast");
 
				});
			}
 
		function togglePlusMinus(id)
			{
 
				$(id).each(function() {
 
					if($(this).find("+ ul").is(':visible'))
						{
							$(this).children("span").text('+');
							eraseCookie(this.id);
						}
					else
						{
							$(this).children("span").text('-');
							createCookie(this.id, 'show', 365);
						}
 
				});
			}
 
});
 
// cookie functions http://www.quirksmode.org/js/cookies.html
 
function createCookie(name,value,days)
	{
		if (days)
		{
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
function readCookie(name)
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++)
		{
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
function eraseCookie(name)
	{
		createCookie(name,"",-1);
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<ul id="demo-menu">
	<li><a href="#">item one</a></li>
	<li><a href="#">item two</a></li>
	<li><a href="#" id="three" >item three<span></span></a> 
		<ul>
			<li><a href="#">item 3.1</a></li>
			<li><a href="#">item 3.2</a></li>
			<li><a href="#">item 3.3</a>
 
			</li>
		</ul>
	</li>
	<li><a href="#">item four</a></li>
	<li><a href="#" id="five">item five <span></span></a> 
		<ul>
				<li><a href="#">item 5.1</a></li>
				<li><a href="#">item 5.2</a></li>
				<li><a href="#">item 5.3</a></li>
		</ul>
	</li>
	<li><a href="#">item six</a></li>
 
</ul>