Category Archives: JavaScript

jQuery: Checking if image is loaded

Triggering some function when an image is loaded is as easy as this with jQuery:

The HTML:

<img src="image.jpg" alt="" id="theimage"/>

Javascript:

$(document).ready(function() {
  $("#theimage").load(function() {
    alert("loaded");
  });
});

If you load your test page a second or third time, you’ll notice that the alert doesn’t pop up. That’s because the browser cached the image and in that case the load event won’t fire. To work around this you could use the complete property of the image:

$(document).ready(function() {
  var $image = $("#theimage");
  if ($image[0].complete) {
    alert("loaded");
  } else {
    $image.load(function() {
      alert("loaded");
    });
  }
});

So in case the image is already loaded the alert pops up right away. Otherwise we bind a function to the load event.

See the code in action on 365 Days or checkout this gist.

DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
Posted in JavaScript | Leave a comment

Capturing keyboard events for div’s and other non-input elements

Last week a friend of mine was claiming that you can’t easily capture keyboard events on non-input HTML elements such as div or span. The fact is: it is easy.

See this demo:

You can use the arrow down / up keys to move the selection down or up. Find a working demo here.

The HTML:

<ul id="list">
	<li class="list-item" tabindex="0">test 1</li>
	<li class="list-item" tabindex="1">test 2</li>
	<li class="list-item" tabindex="2">test 3</li>
	<li class="list-item" tabindex="3">test 4</li>
	<li class="list-item" tabindex="4">test 5</li>
	<li class="list-item" tabindex="5">test 6</li>
	<li class="list-item" tabindex="6">test 7</li>
</ul>

Really the only trick here is to add a tabindex attribute to each list element. This way it can receive the focus and starts to capture keyboard events.

The JavaScript:

$(".list-item").bind({
	keydown: function(e) {
		var key = e.keyCode;
		var target = $(e.currentTarget);
 
		switch(key) {
			case 38: // arrow up
				target.prev().focus();
				break;
			case 40: // arrow down
				target.next().focus();
				break;
		}
	},
 
	focusin: function(e) {
		$(e.currentTarget).addClass("selected");
	},
 
	focusout: function(e) {
		$(e.currentTarget).removeClass("selected");
	}
});
$("li").first().focus();

The keydown event figures out which key was pressed. If it was the arrow up key it selects the previous element and sets the focus on it. For the arrow down key the following element gets the focus. The focusin and focusout events add or remove a css class in order to make the selection more visible.

You can find the complete code of the example here: http://gist.github.com/410789 or by clicking view source in the demo.

DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
Posted in HTML, JavaScript, jQuery | 3 Comments

3 Canvas / Javascript Drawing Tools

1. Harmony by Mr. Doob, great for freehand drawing

2. WebDraw by Steve Hanov. Drawing in XKCD-style. Also nice for informal diagrams. It’s sort of “controlled freehand”.

3. The most complex tool I know of is SketchPad by Color Jack, who is also responsible for quite some other graphic tools.

DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
Posted in JavaScript, Tools | Leave a comment

Drag and Drop between Web Browser and Desktop

For some time already Drag & Drop within the browser is a pretty common feature for web applications. The next step would be Drag & Drop interaction between your desktop and the web application … without using a plugin (Adobe Air, …).

Swell, a Javascript library, seems to be promising: Wouldn’t it be Swell to be able to drag and drop between Web and desktop
Also there is a demo on their web page: Drag and drop files from your desktop to your browser. They say “two browsers are playing well with the demo (Safari 4, Chrome 2+) while others degrades gracefully.

Now, even cooler would be such support in the Google Web Toolkit, but it seems a common approach there is to utilize Google Gears, which again forces the user to install a plugin (except in Chrome, where Gears is an integrated component). Read more about it here and here.

DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
Posted in GWT, JavaScript, Web | Leave a comment

JavaScript: Scope, Closure and what you do with it

One curiosity in our code base are comments in JavaScript files, stating that this variable or function is private. Well, just putting a comment there doesn’t make a variable private, right?

So how to do it?

For that you first need some understanding of scope and closure in JavaScript. In Java, C# or Ruby you deal with block scoped variables. Below a C# example:

public void aFunction() 
{
  string a = "value1";
  if (true)
  {
    string b = "value2";
  }
  a = b;
}

So the string variable a is accessible within the if-statement, but the assignment a = b will cause an exception, because b exists just within the scope of the if-statement.

That’s different in JavaScript. In JavaScript the next code doesn’t cause an exception:

var global = 10;
 
function aFunction() {
  var a = "value1";
  if (true) {
    var b = "value2";
  }
  a = b;
  return a;
}
 
var test = aFunction();

All declared variables in JavaScript are function scoped. So both, a and b, are accessible from everywhere within the definition of aFunction. Variables declared outside of any function are global and thus accessible just everywhere. In fact they become members of the global window object. You really should keep the amount of globals small, otherwise you’ll enter the world of pain when your code grows.
Alright, so we covered scope in JavaScript. Rather in a compact way, but well enough. Let’s move on to closures and consider the next code fragment:

1
2
3
4
5
6
7
8
9
10
var myModule = function(){
  var internal = 5;
 
  return {
    publicProperty: "publicText"
    , getInternal: function() {
       return internal;
    }
  }
}();

This looks pretty much like we assign an anonymous function to the variable myModule. But take a closer look! In fact, we assign the return value of that function to the variable. Note the parenthesis in line ten which executes the anonymous function directly.
The return value is an object literal holding two fields: publicProperty and getInternal. Let’s play with that:

1
2
3
4
5
6
7
8
9
10
var test1 = myModule.getInternal();
// test1 will be equal to 5 after assignment.
 
var test2 = myModule.publicProperty;
// test2 will be equal to "publicText" after assignment
 
// the next line will cause an error, depending on the 
// browser you're using it's different
// but the message is that internal is undefined.
var test3 = myModule.internal;

Most likely you’re not surprised that the assignment in line 4 works. But how does line 1 work? The anonymous function was directly executed, so it already ended and you would expect the variable internal doesn’t exist any more at the point you call myModule.getInternal(). Well, that’s exactly what we call a closure. The variable “internal” didn’t die with the end of the execution of the anonymous function. It’s still in memory, but can’t be accessed other than by functions which were defined within the same scope, like our getInternal function.

As the code above implies you can use this behavior in JavaScript to define private properties, which you can expose by public functions but which are not accessible if not exposed. Besides to the fact that you can realize private function and properties with this technique, using modules / namespaces is a good idea to keep the amount of globals small. Libraries like Prototype use this technique.

You know now, how to write a module in JavaScript and how to realize private members. There are a lot more cool things around this topic and if you’re curious I strongly recommend the reading of Douglas Crockfords articles about JavaScript.

DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
Posted in JavaScript | Leave a comment