Javascript
Lorem ipsum
Tuning Lazy Loader
24 December 2009

I just committed two patches to Lazy Load plugin sent by users. Jeremy Pollock contributed a patch improving scroll behaviour. Before when you scrolled quickly long way down all images above the browser top were loaded. New behavior is to load only those which are currently visible on the screen.
HTML5 Drag and Drop Multiple File Upload
12 October 2009

Previously I experimented with drag and drop file upload with Google Gears. Recently FireFox 3.6 (codenamed Namoroka) was the first to implement File API. It enables JavaScript to interact with local files.
Correction: Ionut G. Stan pointed out that File API was actually available already in FireFox 3.0. What Namoroka introduced is the drag and drop interface for the files. Sorry for the confusion.
Here is how you can implement drag and drop multiple file upload with native JavaScript. No plugins needed. Just plain old new HTML5. Again there is a working demo. You will need FireFox 3.6 to test it. Full source code can be at GitHub.
Drag and Drop File Upload With Google Gears
02 October 2009

Google Gears is an extension which adds new features to you browser. It lets your browser to interact with the desktop. You can store data locally to an SQLite based database. Browser will also have a worker pool for running JavaScript code on the background.
Update 20091007: I updated the tutorial and demo to support dragging and dropping multiple files for uploading simultaneously.
Below is how you can do basic drag and drop file upload. Gears, PHP and jQuery are needed. If you want to try there is a working demo. All source code for the demo can be found from GitHub.
Drag and Drop File Upload With Google Gears
02 October 2009

Google Gears is an extension which adds new features to you browser. It lets your browser to interact with the desktop. You can store data locally to an SQLite based database. Browser will also have a worker pool for running JavaScript code on the background.
Update 20091007: I updated the tutorial and demo to support dragging and dropping multiple files for uploading simultaneously.
Below is how you can do basic drag and drop file upload. Gears, PHP and jQuery are needed. If you want to try there is a working demo. All source code for the demo can be found from GitHub.
Verify Estonian Isikukood With JavaScript
04 September 2009
Yesterday I had to verify Estonian national identification number with JavaScript. The formula is pretty simple. You just have to read it through couple of times to understand. If you need other languages Dmitri Smirnov has examples in PHP, Java and Ruby.
Infowindows With Google Static Maps
13 September 2008
Note! Code shown is now included in Simple Static Maps PHP class. This blog entry is still good for understanding how it was done. Demo code can be considered deprecated.

Previously I showed you how to make a Google Static Map with clickable markers. Several people emailed me to ask how to show infowindow (or infobubble) when marker is clicked. Technique I explain below still needs JavaScript. It is used to open the infowindow. I use jQuery library in the examples.
Image above is just a screenshot. There is a separate page for working demo. Full source code is also available.
Infowindow HTML
First thing we need is HTML code for the infowindow. I wanted it look exactly the same as in Google Maps. I opened a random map and copied the HTML using FireBug inspect console.
Clickable Markers With Google Static Maps
13 June 2008
Note! Code shown is now included in Simple Static Maps PHP class. This blog entry is still good for understanding how it was done. Demo code can be considered deprecated.
Static map is one big image. Markers are embedded inside the image. You can not use traditional <a href=“#”> tags around separate markers. Binding onclick event to separate marker images wont work either. There are no separate markers. Just one large image.
With imagemaps you can specify arbitary areas inside an image which links to given url. Area can be circle, rectangle or polygon. Simple imagemap could look like following:
<map name="marker_map"> <area shape="circle" coords="75,103,12" href="#"> <area shape="circle" coords="122,105,12" href="#"> </map>
With imagemaps we can create clickable markers for Google Static Maps. We need to position an imagemap area over each marker. Problem is how to calculate x and y pixel coordinates for each marker.
Google Maps Without JavaScript Part 2
04 June 2008
Note! Code for zoom and pan controls shown here is now included in Simple Static Maps PHP class. This blog entry is still good for understanding how it was done. Demo code can be considered deprecated.
In previous part we made a Google Map with sidebar navigation which works even JavaScript turned off. Marker locations and sidebar were parsed from two KML files. Beginning Google Maps Applications is a great book to learn about KML and Google Maps in general.
In this second part of tutorial I show you how to add zoom and pan controls. Again, they work without JavaScript. Be sure to read tutorial part one first. Also check the live demo.
Before going forward I would like to answer a question which has been asked more than once:
Q: What is the point?
A: Two reasons. Websites should degrade gracefully. Page should still have understandable content even if JavaScript is turned off. Second reason is just because it is cool.
Add controls to static map
First we add arrows and plus and minus images on a separate layer. This layer is positioned over the static map. I use Google provided images. Mapki has list of all available images.
Howto Show Markers Within Specific Zoom
28 May 2008
Google Maps API offers several nice but relatively unknown shortcuts. One of them is new GMarkerManager class. It enables you to easily control at what zoom levels markers are shown.
In the map above if you zoom in twice a marker appears. Zoom in another two times and the marker disappears. This effect can be achieved by using managers addMarker() method. Instead of using something like:
var marker = new GMarker(new GLatLng(latitude, longtitude)); map.addOverlay(marker);
you must use:
var marker = new GMarker(new GLatLng(latitude, longtitude)); var manager = new GMarkerManager(map); manager.addMarker(marker, min_zoom, max_zoom);
Google Maps Without JavaScript
26 May 2008
We recently did a small Google Maps application for ERGO insurance. It consisted of submitting all their offices to Google Maps. KML export of office data was used to create map at ERGO autoabi campaign site. First version used all JavaScript approach to create the sidebar and map on the page. I was not happy with it. Map page was empty for browsers with JavaScript disabled. Page also took too long to render. Two problems I could not ignore.
Second version was mixture of PHP, JavaScript and new static maps API. Map now works without JavaScript. It renders much faster too. Check the working demo to see yourself.
Importing KML
Google offers GGeoXML library for KML parsing. That I ditched in the beginning. It was impossible to create sidebar navigation with it. First I ended up using EGeoXML. It got the job done but as I said earlier was too slow.
To speed things up I parsed KML files and outputted sidebar HTML with PHP. Simplified HTML and PHP below. Do not mind about # hrefs. They will be replaced with something meaningfull later.
MarkItUp! for Jeditable
08 April 2008
In the heels of autogrow textarea comes next custom input for Jeditable. This time we will use markItUp! universal markup editor by Jay Salvat.
If you are not familiar with Jeditable custom inputs read the introduction. Also see autogrow and timepicker tutorials.
If you are just looking for the code download it here.
Creating custom input
Throughout the tutorial we will be using following code to trigger Jeditable. Note variable called markitupHTML . It holds configuration of used markItUp! tagset. In this example I use slightly modified HTML tagset. For more information on tagsets see markItUp! documentation.
$(".edit").editable("http://www.example.com/save.php", { type : "markitup", submit : 'OK', cancel : 'Cancel', tooltip : "Click to edit.", onblur : "ignore", markitup : markitupHTML });
Again we start by adding custom input type called markitup.
Autogrow Textarea for Jeditable
04 April 2008
Previously i showed you how to create inline timepicker for Jeditable. This time we will create autogrowing textarea. This custom input will adjust its height while you type. Code uses excellent Autogrow jQuery plugin by Chrys Bader.
If this is your first encounter with Jeditable custom inputs you might want to read an introduction to them.
If you are just looking for the code download it here.
Creating custom input
Throughout the tutorial we will be using following code to trigger Jeditable.
$(".edit").editable("http://www.example.com/save.php", { type : "autogrow", submit : 'OK', cancel : 'Cancel', tooltip : "Click to edit.", onblur : "ignore", autogrow : { lineHeight : 16, maxHeight : 512 } });
We start by adding custom input type called autogrow.
Lazy Load With Effects
17 March 2008
You can now add some oomph to your Lazy Loaded images. New effect parameter accepts any jQuery effect. When lazy image is loaded plugin will make it appear using chosen effect. Obviously effects such as fadeOut wont work. Use only effects which make image appear, not disappear.
$("img").lazyload({
placeholder : "img/grey.gif",
effect : "fadeIn"
});
To see code above at work, check fadein demo. Are there any other features you would like to see? Leave a comment.
Related entries: Delayed Loading of Images, Lazy Load Sideways, Preload Images Sequentially With jQuery
Creating Inline Timepicker with JavaScript and jQuery
16 February 2008
Inline editing is not only limited to text and textarea inputs. In this tutorial you will learn how to make inline timepicker with JavaScript. We will be using the usual tools: jQuery and Jeditable.
Before continuing you might be interested in reading introduction to custom input types for Jeditable.
Available methods for creating custom input
When creating custom input type you want to define one or several of following methods. None of them are mandatory.
$.editable.addInputType('example', { element : function(settings, original) { }, content : function(string, settings, original) { }, buttons : function(settings, original) { }, submit : function(settings, original) { }, plugin : function(settings, original) { }, reset : function(settings, original) { } });
All methods receive two parameters. Settings is Jeditable settings hash. Original is the original element which was clicked. Method content() also receives third parameter string which is the value input should be set to. Inside all methods this represents the form.
For this example we will be using three methods.
Style File Inputs With jQuery (and CSS)
24 October 2007
Frontend coders have a life lasting problem. How to explain art director file inputs can not be styled? File Style to the rescue! It is a jQuery plugin which enable you to do just that. Style file inputs.
Code is inspired by work of Shaun Inman with one main difference. This version mimics vanilla file input by showing what file user has chosen.
How does it work?
Plugin wraps vanilla file input with div. This div has button as background image. Image button is aligned with file inputs browse button. File input is then hidden by setting opacity to zero. Chosen file is shown in normal text input which mimics file input. This text input also inherits file inputs class. Use this class to style the text input.
Lazy Load Sideways
12 September 2007
Lazy Load plugin has been quite popular recently. Atleast two Prototype ports have been created. First one by Edd Couchmann. Second one by Bram Van Damme. Congrats guys. Now Prototype people can enjoy lazy loading sweetness too.
I just added most requested feature. Sideways lazy loading of images in wide pages. I guess you could also call it right of fold_. Demo page herewide.html.
As an added bonus you get four new selectors: belowthefold, abovethefold, rightoffold and leftoffold. You can get some performance improvements using these. Attach plugin only to images below the fold with:
$(“img:belowthefold”).lazyload();Or do something with all paragraphs far away right on wide page:
$(“p:rightoffold”).something();There are still some issues I would like to solve. In meanwhile download latest from the project page.
Related entries: Delayed Loading of Images, Preload Images Sequentially With jQuery, Lazy Load With Effects.
Lazy Load Images jQuery Plugin
03 September 2007
Lazyloader is inspired by YUI ImageLoader Utility by Matt Mlinac. After reading YUI introduction I though this is cool! After reading through source thought changed to this needs some jQuery simplicity So I stole borrowed couple of great ideas from Matt’s code. Result is Lazy Load plugin for jQuery.
What does it do?
It delays loading of images in (long) pages. Images below the fold (far down in the page) wont be loaded before user scrolls down. This is exact opposite of image preloading. With long pages containing heavy image content end user result is the same. Page feels snappier. Browser is in ready state after loading visible images. No need to wait for n pictures to load.
From Wikipedia: Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used.
That said Matt’s code does much more. I was only after lazy loading and simplicity of use. If you need more features go for YUI.
Show me more!
Demo page is available. For download and usage instructions info see Lazy Load project page. Or check under the hood.
Related entries: Sequentially Preloading Images With jQuery
Lazy Load Plugin for jQuery
03 September 2007
Lazy loader is a jQuery plugin written in JavaScript. It delays loading of images in (long) web pages. Images outside of viewport (visible part of web page) wont be loaded before user scrolls to them. This is opposite of image preloading.
Using lazy load on long web pages containing many large images makes the page load faster. Browser will be in ready state after loading visible images. In some cases it can also help to reduce server load.
Lazyloader is inspired by YUI ImageLoader Utility by Matt Mlinac. Demo page is available.
How to use?
Lazy Load depends on jQuery (doh!) and dimensions by Brandon Aaron (dimensions is now included in jQuery core). Include them in your header:
<script src="jquery.js" type="text/javascript"></script> <script src="jquery.lazyload.js" type="text/javascript"></script>
and in your code do:
$("img").lazyload();
This causes all images below the fold to be lazy loaded.
Setting sensitivity
There are options for control maniacs who need to finetune. You can set threshold on how close to the edge (don’t push me too far) image should come before it is loaded. Default is 0 (when it is visible).
$("img").lazyload({ threshold : 200 });
Setting threshold to 200 causes image to load 200 pixels before it is visible.
Placeholder image
You can also set placeholder image and custom event to trigger loading. Place holder should be an url to image. Transparent, grey and white 1×1 pixel images are provided with plugin.
$("img").lazyload({ placeholder : "img/grey.gif" });
Event to trigger loading
Event can be any jQuery event such as click or mouseover. You can also use your own custom events such as sporty or foobar. Default is to wait until user scrolls down and image appears on the window. To prevent all images to load until their grey placeholder image is clicked you could do:
$("img").lazyload({
placeholder : "img/grey.gif",
event : "click"
});
Using effects
By default plugin waits for image to fully load and calls show to show it. You can use any effect you want. Following code uses fadeIn effect. Check how it works at effect demo page.
$("img").lazyload({
placeholder : "img/grey.gif",
effect : "fadeIn"
});
Images inside container
You can also use plugin for images inside scrolling container, such as div with scrollbar. Just pass the container as jQuery object. There is a demo for horizontal and vertical container.
#container {
height: 600px;
overflow: scroll;
}
$("img").lazyload({
placeholder : "img/grey.gif",
container: $("#container")
});
When images are not sequential
After scrolling page Lazy Load loops though unloaded images. In loop it checks if image has become visible. By default loop is stopped when first image below the fold (not visible) is found. This is based on following assumption. Order of images on page is same as order of images in HTML code. With some layouts assumption this might be wrong. You can control loading behaviour with failurelimit option.
$("img").lazyload({
failurelimit : 10
});
Setting failurelimit to 10 causes plugin to stop searching for images to load after finding 10 images below the fold. If you have a funky layout set this number to something high.
Delayed loading of images.
Not exactly feature of Lazy Load but it is also possible to delay loading of images. Following code waits for page to finish loading (not only HTML but also any visible images). Five seconds after page is finished, below the fold images are loaded automatically. You can also check the delayed loading demo.
$(function() {
$("img:below-the-fold").lazyload({
placeholder : "img/grey.gif",
event : "sporty"
});
});
$(window).bind("load", function() {
var timeout = setTimeout(function() {$("img").trigger("sporty")}, 5000);
});
Download
Known problems
Due to webkit bug #6656 Lazy Loading wont give you any improvements in Safari. It will load all images you wanted it or not. You can workaround this with
It seems jQuery 1.3.x breaks the plugin for IE. All images get loaded in the background even when they should not. I am working on it. In the meanwhile stay with jQuery 1.2.6.
Also you are using Mint you should have mint tag in the header of the page. Mint tag in the end of the page interferes with Lazy Load plugin. This is rather peculiar problem. If somebody finds an answer let me know.
When asking a question please include an URL to example page where the problem occurs. If you have longer code examples please use pastie.org
Custom input types for edit in place
07 August 2007
I have received many feature requests lately. Most of them have been worth of adding. People have different needs. But I have been worrying about Jeditable becoming feature creep. Thats why I figured out another aproach.
For those in hurry. Check the custom input types demo for some proof on concept inputs.
Write your own input types
Sometimes you need multiple selects. Your form might need special third button which is not submit or cancel. Sometimes you want to use some other plugin such as Date Picker for editing.
There is no point adding separate parameter for all of these. Code would become bloated. Thus I have been working on enabling other developers to add new input types. Think of it as plugins for in place editor plugin.
Preload Images Sequentially With jQuery
05 June 2007
!http://www.appelsiini.net/images/jquery.gif (jQuery)! Here is a small code snippet I use for preloading images for mouseovers. It uses _$(window).bind(‘load’, function() {
Pass Data to Edit In Place With Function
06 April 2007
Small update to jQuery eip plugin. Data parameter is now more flexible. Bug with callback function launching too early is fixed.
In earlier versions you could use functions for two things. To submit edited data to function which takes full control of Ajax request. You could also define optional callback function. This function is called after submitting edited data. Starting from 1.3.1 release you can also use functions as data property. Instead of passing static string you can pass function which generates the data.
In Place Edit With Callback
22 March 2007
jQuery in place edit is now close to have all features it needs. Add some more and it will become feature creep. Most features are configurable. You can even get full control on Ajax request. Just write your own function for submitting and post to this function instead of URL. Smartypants!.
As usual, download latest source or test online.
Using callback function
Now you can define optional callback function. This function is called after form has been submitted. Callback function receives two parameters. Value contains submitted form content. Settings contain all plugin settings. Inside function this refers to the original element.
$(".editable").editable("http://www.example.com/save.php", { type : "textarea", submit : "OK", }, function(value, settings) { console.log(this); console.log(value); console.log(settings); });
In Place Editing With Selects
13 March 2007
Several people already asked support for selects and possibility to pass CSS class or styles as parameter to jQuery inplace editor. Here they are.
Big thanks goes to Mathias Henze for providing patches and ideas making this release possible!
For those in hurry: test and grab the latest source.
NOTE! JUST FOUND OUT THIS RELEASE HAS PROBLEMS WITH IE. WILL RERELEASE IN FEW HOURS AND KICK MYSELF THREE TIMES FOR NOT DEBUGGING IN WINDOWS!
How to use selects?
You can use selects by giving type parameter value of select. Select is built from JSON encoded array. This array can be given using either data parameter or fetched from external URL given in loadurl parameter. Array keys are values for <option> tag. Array values are text shown in pulldown.
Jeditable 1.1.1 - Minor Bugfixes
15 February 2007
Latest release of javascript in place editor plugin has some minor bugfixes. In near future postload and getload parameters will be deprecated in favour of loadurl and loadmethod.
Fixed bugs are:
- Cancel button now works even when onblur is set to ignore. Thanks to Thomas Mann for providing the patch.
- Plugin does not break the chain even when attached to nonexistent element. In other words it returns this instead of false in case of failure.
As usual test and download plugin.
Debugging PHP With Firebug
08 February 2007
Logging PHP and JavaScript errors to same window makes debugging easier. It also might be the cure to cancer and bring world peace. In general…
In a recent PHP + JavaScript project I realized how annoying it is to have debug information in more than one place. For PHP I use PEAR::Log package. Log is written to file. For JavaScript I use Firebug. Log is written to Firebug console. When something goes wrong you must switch between browser and terminal windows.
There must be a better way. I like both PEAR::Log and Firebug. Obvious thing was to combine them. Result is Firebug handler for PEAR::Log. It can currently be found only in CVS. Hopefully be handler will be included in next release of PEAR:Log package.
Example PHP usage below.
$log = &Log::singleton('firebug', '', 'PHP',
array('buffering' => true),
PEAR_LOG_DEBUG);
$log->log('Debug lorem ipsum.', PEAR_LOG_DEBUG);
$log->log('Info wisi enim ad minim veniam', PEAR_LOG_INFO);
$log->log('Warning est usus legentis in', PEAR_LOG_WARNING);
$log->log('Error est notare quam', PEAR_LOG_ERR);
If you have Firebug installed, enable it and check Log Firebug test page. You can also redirect all PHP errors to Firebug console.
UPDATE 20070208: You might want to check FirePHP which provides different approach. FirePHP is Firefox extension built on top of Firebug. It modifies request headers to include Accept: text/firephp. Debug data is sent back using text/firephp section of multipart/mixed HTTP response. Using FirePHP is more complicated but at the same time it can provide you with more flexibility.
Jeditable 1.1.0 - Compatible with jQuery 1.1
17 January 2007
New release adds inplace editing capabilities for recently released jQuery 1.1.
In addition to compatibility changes new or improved options are:
- data : string Alternative to postload and getload. Instead of fetching content from external resource it can be passed as parameter.
- cancel : string Value for optional cancel button.
- submit : string Empty value does not default to ‘OK’ anymore. If you want to have submit button you have to define this option.
As usual test and download plugin.
Edit In Place With Effects
30 December 2006
Graphical effects can be used to improve user experience.
People have been asking me to add configurable effects into Jeditable. I believe in writing reusable code. This also means I do not want to force people use anything specific including graphical effects I happen to like. I believe people should be able to use any 3rd party effects they want to use.
Luckily jQuery makes this easy to implement. Just add effects you want to same element selector you make editable.
For example you want to change background colour to yellow when move mouse over editable area:
$(document).ready(function() { $(".editable").mouseover(function() { $(this).css('background-color', '#ffffd3'); }); $(".editable").mouseout(function() { $(this).css('background-color', '#fff'); }); $(".editable").editable("http://www.example.com/save.php", { indicator : "<img src='img/indicator.gif'>", type : "textarea", tooltip : "Click to edit." }); });
Jeditable 1.0.0 - Doubleclick to Edit
21 December 2006
First stable version of jQuery Javascript in place editor is out of oven. Existing api will be frozen. I will add new features in near future.
I only added one bugfix and one feature since last release candidate. These are:
- Width and height setting of auto now works with all input types.
- New configurable option submit controls value of submit button. Empty value means no submit button.
Textareas still have default submit button with value ‘OK’.Scrap that. I do not want force users to have submit button when using textareas. Besides when onblur=submit the submit button is not even needed.
New submit option is used as follows:
$(document).ready(function() { $(".edit").editable("http://www.example.com/save.php", { type : 'text', submit : 'Save changes' }); });
As always test and download plugin.
Jeditable 1.0.0RC1 - Configurable OnBlur Event
31 October 2006
Thanks to community support Jeditable now has additional features and new bugfixes. First stable release is almost there.
New release of jQuery in place editable plugin fixes following bugs:
- When textarea size was set to auto width and height were incorrectly set. To be exact px was missing from the property.
- Also when using auto size the width and height was only calculated once. Thus if you edited content more than once, textarea size did not change according to new content.
- All instances of $ are now changed to jQuery.
- When attaching Jeditable to nonexistent element elem has no properties error is no more thrown.
Thanks to Nagy Attila Gabor and Gary for providing patches!
Additionally new configuration parameter onblur was added. Possible values and corresponding behaviors are:
- onblur : ‘cancel’ Clicking outside editable area cancels changes. Clicking OK button submits changes.
- onblur : submit’ Clicking outside editable area submits changes.
- onblur : ‘ignore’ Click outside editable area is ignored. Pressing ESC cancels changes. Clicking OK button submits changes.
As always test new features and download plugin.
Jeditable 0.9.2 - Ideas From EditInPlace
11 October 2006
While looking at Joseph Scott’s EditInPlace I realized Jeditable missed one important thing. Possibility to configure event which starts editing. Default is click.
This is now implemented via options[event]. You can use any jQuery events such as click, dblclick, mouseover or mousemove. Out of these example event the first two are naturally the most usefull ones. Additionally some internal changes were made in order to follow jQuery plugin authoring guidelines better.
Download latest version of jQuery in place editor plugin while its hot!
Jeditable 0.9.1 - Now With Tooltips and Autosizing
30 September 2006
Just released next version of jQuery inplace editor plugin. This version has two improvements. Textarea input element can be automatically sized to match the size of edited element. This is also default behaviour. Additionally an optional tooltip via title attribute is supported.
Jeditable 0.9.0 - In Place Editor for jQuery
29 September 2006
It has been a while since I last was really excited about something. Few days ago I found jQuery.
jQuery states itself as New Wave JavaScript. I have had experience with prototype and script.aculo.us. Both are great libraries. However I never felt comfortable them. I just used them.
With first impression about jQuery’s syntax is bit confusing:
$(document).ready(function() { $("a[@href*=/foo/bar]").click(function() { alert('Click.'); }); });
After reading that jQuery’s main developer John Resig is also a Perl coder it all makes sense. I assume the fact that I did code Perl “back in the days” makes me feel comfortable also with jQuery.
