There are security concerns when communication between different HTML windows or frames occurs, that is why the communication is one way (from the child to the parent) and only if both windows are from the same domain.

Enter postMessage, an HTML5 feature, that allows sending messages that will be received as message events. Checking the origin (very important) and using with care the event parameter data, a simple string, is all that is required for a good relationship between friendly parties. window.postMessage is or will be implemented in Firefox, Opera, Safari, Chrome and even IE8.

Here is a link that describes the feature: Cross-Window Messaging.

Also, check out the jQuery cross-browser plugin that uses hashes to send data back and forth (naturally, the same mechanism should be implemented at both sides)

I've heard about LESS yesterday so I thought about how I would use it in my projects. Using a .NET http handler is just fine, but I was thinking of a simpler approach, so I created jQuery.cssLess, a jQuery plugin that reads the css and interprets it. You can find it at Github.

Current version supports variables, mixins and nested rules. I am wondering if it is even worth it to implement operations. It may bloat the plugin too much. What do you think?

Little did I know, someone else was trying a js centric approach to this. The project is called less.js and it's made by cloudhead. You can find it at GitHub.

If you are using LESS and decide to use jQuery.cssLess, please leave me a message about it and whatever your opinions are.

This weekend I participated in an advanced Javascript training (and workshop, as it turns out) gratiously offered by Frontend Force, a company specialised in professional Javascript code (not web design). That means they do stuff for browsers, for cell phones and even (if you didn't already know) for the server-side platforms running on Javascript. At this moment they are hiring for positions in Berlin (no remoting) and are looking for true IT professionals, preferably with strong Javascript knowledge. So contact them... now! They also do consulting.

The trainers were Dawid de Rosier and Piotr Zwolinski, both from Poland, more the former than the latter, and I have to say that I've learned quite a few new things and understood better things I already knew, just from Dawid's 6 hour presentation. The training was great also because it happened in the weekend, so I didn't have to feel guilty for skipping work from my regular job or to feel bored doing nothing in the weekend. I say 6 hour presentation because the next day we did an application in typical agile manner, working in teams and applying the things we've learned. The project can be found on the net, it is open, and it is a ... shopping cart. I know, terribly boring subject, but the code was the focus and the code was cool (at least my part, of course... :) ). The link for the project is this: 3F Commerce. But enough of that, after all the coding experience cannot be translated into a blog post, I will talk mostly about the presentation in the first day and the things I've learned there.

It should be interesting enough to get your attention that the training was about the Javascript programming language not its use in the browser. After all, Javascript is a stand alone language and, as you will see to the end of the post, used in a lot more contexts. Its roots stem from Lisp, Scheme (hence the title of the post), Self and a bit of Perl and the syntax is C like because it was cool at the time (and it still is, maybe the Perl guys should have thought of that). The name Javascript itself was used as a marketing ploy because Java was all the rage back then.

As a dynamic language its most proeminent features are the protoype based inheritance and the closure/lambda approach to variable scope. One of the most important things, if not the most, that I have learned is that each function remembers the context in which it was created. For procedural style of programming in Javascript, the context is the global one, so many people don't know or care about it. Short example:

function createMyFunction() {
var x = 11;
return function () {
alert(x);
};
}
Now if you execute var f=createMyFunction(); f(); you get a message box with a value of 11. The x variable is remembered, even if in the scope of a function that is not longer in execution. I will show you later how you can create truly private members of a class or function. Well, in Javascript there are no classes, only functions, but they have a different meaning from, let's say, functional programming.

First of all, we talked about the variable scope. Javascript does not have block scope. That's important. It means that if you do something like

if (condition) {
var x = 10;
}
alert(x);
you will get an alert with the value 10. The only scope is function scope in Javascript, meaning that to get the same effect as a block scope, the previous example should have looked like this:

if (condition) {
(function () {
var x = 10;
})();
}
alert(x);
and now you would get undefined.

Then we delved into apparently obvious stuff like

var x = 'true';
if (x) alert(x == true);
The code above would display false. Why? because there is an equality between different types and they are both converted into... numbers! true gets an internal representation of the true value, while 'true' gets the value NaN, as it is not a number. And they are not equal. The condition itself is satified, because x is not empty.

With these two things explained (better than I can here) it was concluded that global variables should be avoided, while in order to do equality one should use the triple equal sign === which compares not only the values, but also the types. It is also much faster, as it doesn't try to convert anything. One good use of the normal operator == is when comparing to null. Let me exemplify:

null == null //true
undefined == null //true
0 == null // false!
This is better than using a variable as a condition of 0 would not execute an if block.

The next bit was about functions and how you can use them as classes. Here it was explained how functions remember their environment. This kind of functions are called closures. An interesting thing you need to understand in Javascript is that the closer the variable is from your execution scope in the execution hierarchy, the faster its access is. Let's take a very common function: document.getElementById. Here is a faster version of it:

var byId = (function () {
var D = document;
return function (id) {
return D.getElementById(id);
};
})();
This is faster because byId is a closure and it gets a reference to the document (slow global variable) at its creation and remembers it in the environment. Every time you execute it, it will use the closest scope to find the variable and it will be faster. On my Internet Explorer 8, byId is faster than document.getElementById with 22%.
A very important thing to see here is that D is not accessible anywhere outside the function. Not even byId.toSource would show where D is created. So, indeed, it is a private member of the function!

A lot of stuff was discussed about random but important quirks of the language.
  • There are two main categories of types in Javascript: primitives and objects. For example '5' is a string primitive, while new String('5') is an object. The String object has methods, like toLowerCase. Yet '5'.toLowerCase works, because the primitive is automagically converted into the corresponing object.
  • The instanceof operator checks if a certain object is of a certain type. Kind of useless, since each object can have whatever members one defines dynamically and implemented in whatever way. Needless to say '5' instance of String is false. Or maybe not so needless :)
  • Each function has a special local variable called arguments, which represents an array of arguments passed to the function (no matter how many were defined in the function signature). This object has some special members like arguments.callee, which represents the function being executed. See how it is used to create an anonymous recursive function:

    var x = 10;
    (function () {
    alert(x);
    x--;
    if (x > 0) argument.callee();
    })();
  • Another fun thing is that there is a default undefined object. You can compare something with undefined: if (x === undefined). Unfortunately, undefined is not a reserved word. So this code is valid: undefined=10;. Just compare the type to the string 'undefined': if (typeof(x)==='undefined').
  • Most Javascript coders are familiar with the in keyword that is used to create foreach like loops: for (var key in hash) do(hash[key]);. Very few know that 'in' is also an operator: if ('x' in a) { do (a.x); doAgain(a['x']); }. It checks for the existance of a property in an object or its prototype. If you want to know if the property if of the object or of the prototype chain, use the hasOwnProperty method. Prototypes will be explained shortly.


I've spoken a little about private members, but now I will tell you about inheritance! Yes, it is possible in Javascript, who would have thought? :) Only it is a prototype inheritance.

What are prototypes? Each function has an object that would be used to return default values for any of its instances called prototype. It's kept as a reference, so only one prototype object for any number of instances. This prototype, as almost anything in Javascript is writable, replaceable, extendable. Let me give you a short example:

function MyClass = {};
var m = new MyClass();
alert(m.someProperty);
MyClass.prototype.someProperty = 'set';
alert(m.someProperty);
m.someProperty = 'overwritten';
alert(m.someProperty);
delete m.someProperty
alert(m.someProperty);
This code defines an empty function called MyClass. You use it as a type and create instances of it by using the new operator. The first alert will show 'undefined' because the instance has no someProperty member. We then set it in the prototype and so it will be seen in any of the instances of MyClass, so the second alert will show 'set'. Then we set the actual value directly in the object. The third alert will display 'overwritten'. Delete the value (unset it) and the fourth alert will display 'set' again.

So what about inheritance? Let me give you the short story:

function MyClass(msg) {
// optional
// ParentClass.apply(this,msg);
}
var F = new Function();
F.prototype = Parent.prototype;
MyClass.prototype = new F();
MyClass.prototype.constructor = MyClass;
Here we create a MyClass object that inherits from ParentClass. In its constructor we apply the ParentClass function in the context of the MyClass instance (if we want to), then we create a new temporary F function in order to copy the prototype, but not whatever values are set via the constructor and we set an instance of it as the prototype for MyClass. Then we recreate the constructor of MyClass in its prototype, since it was overwritten.

Too fast? Let's examine what would happen when a new MyClass instance is created:
var m=new MyClass(msg);
  • the instance of the F temporary class which holds any and all of the members in the prototype of ParentClass is the prototype of MyClass
    the MyClass prototype is different from the ParentClass prototype, so any changes done to it are not reflected to the ParentClass prototype
  • the constructor of MyClass (itself) is executed in the context of the new instance which executes the constructor of ParentClass in the same context and thus sets anything that the parent class would set to its own instances


Now the new instance has all the default members an instance of the ParentClass would have and its own members or overwrites of the existing ones. Inheritance!

To end this over long post, I will give you a piece of code of a class that inherits another class, has private members, setters, getters, etc.


(function () {
// base class
Animal = (function () {
// private member
var _version = '0.9';
return function () {
// priviledged getter (public, with access to the private member)
this.getVersion = function () {
return _version;
};
// priviledged setter
this.setVersion = function (value) {
_version = value;
};
};
})();
// prototype public method (only one referenced in all instances of Animal)
Animal.prototype.MakeNoise = function () {
throw "Abstract animal class must be inherited";
};
// prototype public method
Animal.prototype.getType = function () {
throw "Abstract animal class must be inherited";
}

// child class inherits from Animal
Duck = (function () {
// private member
var _type = 'Duck';
return function () {
// call the base constructor
Animal.call(this);
// priviledged getter (no setter for _type!)
this.getType = function () {
return _type;
}
// set version using base class method
this.setVersion('1.0');
// hide base class method (emulation of protected methods.
// of course, one can use delete a.setVersion
// and then access the base method)
this.setVersion = function () {}
};
})();
// copy the base class prototype
var F = new Function();
F.prototype = Animal.prototype;
// set it as the parent prototype
Duck.prototype = new F();
// prototype public method
Duck.prototype.MakeNoise = function () {
alert('Quack!');
};
})();

var a = new Animal();
alert(a.getVersion()); // 0.9
try {
alert(a.getType()); // error, abstract getter
} catch(e) {
alert("error! (" + e + ")");
}
try {
a.MakeNoise(); // error, abstract method
} catch(e) {
alert("error! (" + e + ")");
}
a = new Duck();
a.setVersion('999'); // no effect, since setVersion was replaced with empty function
alert(a.getVersion()); // 1.0
alert(a.getType()); // 'Duck'
a.MakeNoise(); // 'Quack!'


Some more information about tools that one can use in javascript programming:
Aptana - standalone js IDE and also Eclipse plugin
Rainbow9 - javascript IDE as a web application
QUnit - unit tests for javascript
JsLint - checks the validity of your javascript code online
jsbeautifier.org - reformats javascript code
Closure Compiler - minimize javascript code
JSA - obfuscator (it's an untranslated Chinese site, just use the last button)
Xmake or Rmake - code builders
NodeJS - javascript powered server side framework
jsDocs - makes documentation (specific comment formats are required)
JS TestDriver - unit testing and integration
Persevere - makes the connection between javascript fron ends and server side databases

I spent several hours debugging an error that gave this exact error message: 'null' is null or not an object. Well, duh! The problem here is that the project was an ASP.Net project, with a large number of files that interacted in innovative and weird ways with the ASP.Net Ajax framework. So going line by line was a problem. Also, the Javascript debuggers stopped in a finally block that had nothing to do with the error.

As a side note, the only debugger that showed where the error originated was the Chrome debugger (and probably the FireFox one, but I didn't get to try it). The problem with Chrome is that it only gave me the file and line number in a "minimized" js file, so I had no clue on what was happening.

Ok, to cut it short, the error appeared in a line like $get('someId').value=... An element with the id someId did not exist, therefore the result of the function was null. Setting the value resulted in the error.

Conclusion: 'null' is null or not an object is an error that occurs when member access is requested on a function result without it being stored in a variable. Look for stuff of the form someFunction(params).member. It is a bad form anyway; store the someFunction result in a variable and then access its members: var x=someFunction(params); if (x) //doSomethingWith x.member

Internet Explorer added something called expression to CSS, something purists have booed at for mingling javascript and CSS. Well, boo back! I happen to like stuff that can solve problems. If I were at Microsoft I would create an entire subset of javascript and css functionality. But hey, that's just me.

Anyway, I have decided to use expression to run an initialize function on newly created elements. It would work like this:
initialize:expression(window.initializeElement?initializeElement(this):null);
This CSS bit tells Internet Explorer (and none of the other browsers) that the initialize style property should get the value of the initializeElement function every time the browser refreshes the layout of the element. In the function itself I would do something like this:
function initializeElement(elem) {
if (!elem.style.initialize) {
doSomethingWith(elem);
}
return true;
}
This basically executes doSomethingWith on each element matched by the CSS rule and only once.

Good theory, but in practice it was terribly slow and, after a while, it managed to kill Internet Explorer with a strange System.AccessViolationException: Attempted to read or write protected memory error.

What happened? The slowness, I gathered after a while, was caused by the function doSomethingWith because it changed the style of the element. That meant that the css rule was being applied again before the function ended and returned true. Changing things to:
function initializeElement(elem) {
if (!elem.style.initialize) {
elem.style.initialize=true;
doSomethingWith(elem);
}
return true;
}
fixed it.

The error that killed Internet Explorer was even stranger. After a while I narrowed it down to using jQuery. I have no idea what it did, probably trying to access computedStyle or something like that. The thing is that changing an $(elem).height() with elem.offsetHeight solved it.

I've encountered this situations a couple of times, what happends is that, at the end of the body of the document or of a major element like a form or a page wide div, sometimes (I haven't really been able to reproduce it at will) hidden elements start having height. This includes hidden divs and spans and even script elements. It seems to be happening mostly on Internet Explorer, but the behaviour has reportedly also been found on Opera and even Chrome.

For a specific example, I had this page with a lot of script tags at the end of the form element. Curiously, only when some spans with display:none were added at the end of the body element the problem would become evident as the height of the page would increase by 12px and a vertical scrollbar would appear. I also encountered the issue when I moved, via script, the calendar popup div for a datetime editor at the end of the body element to solve a positioning issue. Both were happening in "quirks mode" because I am forced to use a HTML 4.01 Transitional doctype.

To me it seems that the browser considers that script tags have no layout, so there is no problem to put them all one above the other in that extra 12px bit, but it does consider it needs to reserve that 12px space. Well, does it have layout or doesn't it?

I looked on the web for people with similar problems and I have encountered very few that actually tackled it. Here is one example of a solution from the Perishable Press blog: Prevent JavaScript Elements from Breaking Page Layout when Following Yahoo Performance Tip #6: Place Scripts at the Bottom.

For short, the solution in the above link is to place all the scripts at the end of the page, but inside a hidden div element. If you have access to all the layout, that is a great solution. However, I found that I could not use it, since the scripts were not added by me and I had no control over their placements. So I found an alternative solution, after noticing that the extra size would dissappear if the popup div of a control was shown.

Well, my solution is quite obvious: if there are issues with hidden and script elements placed at the end of the page, then why not try to add an element at the end of the page and thus make hidden elements NOT be at the end? :)

A short jQuery script did it for me:
$('script').each(function() { 
if ($(this).height()>0 && !$('form').children(':last').is('div.scrollFix'))
$(this).parent().append('<div style=\'position:absolute;background:transparent;width:0px;height:0px;line-height:0px;font-size:1px;\' class=\'scrollFix\' />');
});
or, in normal Javascript:
var scripts=document.getElementsByTagName('script');
for (var i=0; i<scripts.length; i++) {
var script=scripts[i];
var parent=script.parentNode;
var lastChild;
if (parent&&parent.childNodes.length>0)
lastChild=parent.childNodes[parent.childNodes.length-1];
var isFixed=(lastChild&&lastChild.tagName&&lastChild.tagName.toLowerCase()=='div'&&lastChild.className=='scrollFix');
if (script.offsetHeight>0&&!isFixed) {
var div=document.createElement('<div style=\'position:absolute;background:transparent;width:0px;height:0px;line-height:0px;font-size:1px;\' class=\'scrollFix\' />');
parent.appendChild(div);
}
}


The script is improved by actually scanning the last element of the parent element for the hidden div so that it doesn't add a zillion divs, one for each script tag. However, it doesn't cover the situation where other elements, rather than the script elements, cause the problem. However, the principle remains sound.

I had this situation where in Internet Explorer, in quirks mode, I would open a dropdown calendar (so showing an absolutely positioned element that was until then hidden) and the scrollHeight of the entire page would increase by a magical 19px.

This was caused by a fix for another problem, where the displayed calendar would not position itself under the text input element where it should have positioned, so I made it so that the displayed calendar would be the last child of the body element. This way it would always show in the correct position, but displaying this situation when elements were trying to fit in the height of the page.

I could not find the cause other than a problem in the Internet Explorer render engine, but I did find a fix. Instead of placing it at the end of the body element, place it at the beginning. With jQuery that simply translates into:
if (!elem.parent().is('body')) $('body').prepend(elem);
Notice my use of prepend instead of append.

It started with a simple request for a custom control to perform some validation. Seems easy enough, but it is not. Sure, there is an easy solution and that is to create a composite control, containing the original control and a normal validator, but that means you don't inherit from either control and you have to copy all the properties and methods you are interested in. If, as I did, you do not like this solution, you will soon find out that there are a lots of obstacles to be conquered if you want all the features of a validator, the first of which being that a control cannot easily change the Controls collection of its parent. It would be bad design. Therefore simply adding a Validator from inside the control does not work.

Let's start with what others did: Self Validating ASP.NET Text Box. This CodeProject article shows how you can build a control that is validated only on the server side and implements the IValidator interface. However, you will notice that it did not implement the ValidationGroup behaviour. And that is due to a simple fact: there is a method of the Page class called GetValidators(string validationGroup) that is used all around ASP.Net. It looks kind of like this:

public ValidatorCollection GetValidators(string validationGroup)
{
if (validationGroup == null)
{
validationGroup = string.Empty;
}
ValidatorCollection validators = new ValidatorCollection();
if (this._validators != null)
{
for (int i = 0; i < this.Validators.Count; i++)
{
BaseValidator validator = this.Validators[i] as BaseValidator;
if (validator != null)
{
if (string.Compare(validator.ValidationGroup,
validationGroup, StringComparison.Ordinal) == 0)
{
validators.Add(validator);
}
}
else if (validationGroup.Length == 0)
{
validators.Add(this.Validators[i]);
}
}
}
return validators;
}
Notice anything? There is no mention of IValidator, instead only BaseValidators are sought and the reason the IValidator approach works at all is the line before last where a validator is added to the list if the validationGroup parameter is empty. That is, it will work with IValidators but only on Buttons or other postback controls that have an empty ValidationGroup.

So let's start from the idea of the original article: an IValidator TextBox control with server validation only. For simplicity I will compare the value of the control with a constant string and fail the validation if the comparison fails.

Click to expand


You notice that the entire logic of this method is that the validators in the Page.Validators collection will be validated when need arises. In order to implement the ValidationGroup behaviour, we need to either fool the GetValidators method or to actually add a BaseValidator to the collection, not the IValidator control. I would have preferred the first method, but GetValidators is executed not only in Page.Validate but, being public, can also be executed in other situations (and in fact it is called by every control that wants to cause a postback).

My first attempt was to simply add a dummy validator to the collection, with the proper ValidationGroup set. It worked for the client side (we'll get to that) but then it failed miserably when Page.Validate tried to loop through the collection. I was forced to create my own validator control that inherits from BaseValidator. Do not worry, though, it is very lightweight and does not need to be added to the Controls collection. Here is the source:
Click to expand

public class DummyValidator:BaseValidator
{
private readonly IValidator _realValidator;

public DummyValidator(IValidator realValidator)
{
_realValidator = realValidator;
}

protected override bool EvaluateIsValid()
{
_realValidator.Validate();
return _realValidator.IsValid;
}

protected override bool ControlPropertiesValid()
{
return true;
}
}


Note: the following code has a property called ValidationGroup. The TextBox already has it, for its own AutoPostBack behaviour. I left it there, though, because you might want to use this on a control that doesn't have it natively.

Now the code for the ValidatedTextBox class looks like this:
Click to expand

private DummyValidator _dummyValidator;

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Page != null)
{
_dummyValidator = new DummyValidator(this){ValidationGroup = ValidationGroup};
Page.Validators.Add(_dummyValidator);
//Page.Validators.Add(this);
}
}

protected override void OnUnload(EventArgs e)
{
if (Page != null)
{
//Page.Validators.Remove(this);
Page.Validators.Remove(_dummyValidator);
}
base.OnUnload(e);
}

private string _validationGroup;

public string ValidationGroup
{
get
{
if (_validationGroup == null)
{
if (ViewState["ValidationGroup"] == null)
ValidationGroup = "";
else
ValidationGroup = (string) ViewState["ValidationGroup"];
}
return _validationGroup;
}
set
{
_validationGroup = value;
ViewState["ValidationGroup"] = value;
}
}


So the ValidationGroup is now working on the server side since there is an actual BaseValidator in the Validators collection calling the Validate method of our control. Since the DummyValidator class doesn't implement any specific behaviour, it can be reused for any type of validated control.

Now for the client side part. The client validation scripts work with a javascript array called Page_Validators. The validators are rendered as span elements (where the error message is displayed) and the array holds all these elements, with some extra properties like isValid, errorMessage, evaluationfunction, controltovalidate, validationGroup, focusOnError, enabled and display. The first three are like the IValidator members, only in javascript, controltovalidate is the client id of the control to be validated while focusOnError is used to scroll the page/container in order to see the invalid control without looking all over the page to find it.

All the ASP.Net validation functions are in a javascript file called WebUIValidation.js and embedded in the System.Web.dll library. We need to load it in order for validation to work. Then we need to render a span element and set its attributes. Lastly, but most important of all, we must create a function that will evaluate the validity of the control.

I will just post the entire source, since all the client code is practically copied from the BaseValidator code.

Click to expand


There are several things you need to take care of.
One of them is the client display of the validators. Normally, a validator's span element is rendered with the ErrorMessage as inner html. The ASP.Net framework then changes the visibility of the span depending on the validity of the control. I have chosen to not render the error message, as I wanted a different behaviour (in this case, a red background). The span element is still shown and hidden, but being empty, there is no visible effect.
Another thing is when you would use validation summaries. The error message is being rendered as a property of the span. It WILL be used in the summary, even if it is not normally displayed.

This code will work with almost no change for any control, so you could encapsulate it into a ValidatorHelper class or something. The only variants are the Validate method and evaluatefunction function.

Also note that having inherited from BaseValidator, I bypassed the normal functionality of the default validator controls. If you want to inherit from one of those, like RegularExpressionValidator, you might encounter problems, especially for controls that are not normally validated and for which the normal validator controls try to get their value. Take a look at the ValidationProperty attribute that you might need to use to decorate your control in order to work with default validators. Also, the javascript behaviour is to look for a control that has a value attribute. If not found it searches deeper into the children. So if you want to use a default validator, you might want to add script to keep a value attribute updated on the validated control HTML element.

And that was all.

I had this expand/collapse div on which I was using slideToggle to make it look good. However, in quirks mode (HTML Transitional 4.01 DocType) and on IE7 the div would briefly pop up after collapsing, showing an annoying flicker. It seems that Internet Explorer has a problem rendering stuff with height 0px.

The solution I found: replace target.slideUp(speed,callBack) with
var h = target.height();
var cssHeight=target.css('height');
target.animate(
{ height: '1px' }, speed, function() {
target.hide();
target.height(h);
target.css('height',cssHeight);
callBack();
}
);
I have also created a jQuery ticket to suggest they use the same method in the library itself.

Update 1 Sep 2009: I have added the cssHeight variable to restore the actual css height settings, not just the height.

Update 21 May 2011: commenter Mads shared a more elegant solution in the form of this script:
(function(){
// Define overriding method.
jQuery.fx.prototype.hide = function(){

// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.hide = true;

// Begin the animation
this.custom(this.cur(), 1);
}
})();
used anywhere after the jQuery include. Thanks, man!

I have this very precise requirement I am working on: a collapsable panel that has rounded corners of fixed size and a background image or a gradient, both needed to stretch with the panel, which would be vertically resizable by javascript. Also, the HTML 4.01 Transitional DocType will be used on pages. The only respite given is that the solution should work only on Internet Explorer.

I have first tried some jQuery alternatives, but I am not happy with them. Even if the rounded corners would have been what I was looking for (and they were not), the background stretching is a difficult feat to master in HTML. Even so I have cropped up something that takes the entire content of the panel and relatively positions it over an absolutely positioned image that is then stretched by javascript to its needed dimensions. However, all this relative and absolute positioning requires a lot of event driven javascript (when the events themselves are not really there, so I must also create new browser events!) and it has been shown to break either layout or functionality like the one for collapse.

Enter VML, an obscure web technology from Microsoft that has a RoundRect object that can have a fill of an image OR a gradient, stretched to the full size of the element. Can you see it? I was already planning the blog entry, detailing the masterful ASP.Net control that would change the world of web development forever.

Back to real life now. First of all, the RoundRect element does have an arcSize property that determines the percentual size of the rounded rectangle. By percentual, I mean that resizing the element would lead to larger corners. I don't need that. Another nice surprize was that I can't either read or write the arcSize property from Javascript, it throws an error. People have complained about it before and their solution was to disconnect the element from the DOM, change the arcSize, then add it back into the DOM. It didn't work for me.

After wasting about half a day with this, I concluded that the RoundRect was a lost cause. Enter Shape! A Shape is a VML element that can take any shape determined by a path. The path has interesting primitives like qx and qy which mean "draw an arc to this position". It appears that a Shape can easily take the place of the RoundRect. What was even nicer, the path attribute could be changed at will by javascript.
<v:shape strokecolor="blue" strokeweight="1" coordorigin="0 0" coordsize="203 103" style="width:200px;height:100px"
path="m 2,0 l 198,0 qx 200,2 l 200,98 qy 198,100 l 2,100 qx 0,98 l 0,2 qy 2,0 e"></v:shape>
The code above is a 2 pixel rounded corner rectangle of size 200 by 100. To add a stretched background image or gradient, a v:fill element must be added as a child of the shape and you are done!

I was extatic, finally having solved the problem that had haunted me for days, until I noticed that, unless I specify the width in pixels, the shape would behave really strange. I was commited not only to a panel that needed to be defined as percentual or expanding with the content, but also to HTML 4.01 Transitional DOCTYPE. In this particular situation, placing two shapes in a table, let's say, even if the table size was specified or, indeed, the sizes of the TD elements, in percentages or pixels, the shape would just expand to its maximum possible width.

I got stuck here. The control worked perfectly when the width was specified in pixels. Anything else just throws a big wrench into the works and makes it wanna go boom. In a fit of anger, I just replaced the obsolete doctype with the modern XHTML 1.1 one. And it worked, but only on Internet Explorer 8, not any of the previous versions of the browser.

Therefore my only option now is to either abandon the technology completely or to convince people to change the DocType for all their legacy pages. How fun is that?!

And before you write the usual crappy "Microsoft sucks! Internet Explorer sucks!", try giving me a solution for my request that would at least work in another browser. Was it so difficult to recognize the need for a stretched background image and custom shaped containers ?!

Now, that title doesn't much, but it's the only one I could think of, because I haven't yet determined the source of the problem. Baiscally, what happends is that there is a difference of behaviour between style included directly into the page and actually using javascript to add to the head of the page a dynamically created link element.

I have no idea what exactly is going on, but I will try to explain it based on the evidence. There was this menu control, an Infragistics Web Menu from the NetAdvantage 9.1 suite, that, given the right styling, would look exactly like what I wanted. After setting that style in a css file I decided to load it using a javascript dynamic load just in case the control would be rendered only on asynchronous postbacks. And it worked perfectly. In IE8, Chrome and FireFox. However, when tried on IE7, it exibited the strange behaviour that, on mouse over, the entire table that the menu was rendered as expanded to fill the screen and was completely blank. After extensive attempts to capture the element with Internet Developer toolbar I noticed that the border-bottom-width and border-left-with were abnormally high, like thousands of pixels.

As of now I know not the cause of this. I can tell you, though, that moving the same style from the dynamically loaded CSS into a statically loaded one or by copying that style in a style tag in the page fixed the issue. I really hope it helps someone lose less days of their lives attempting to see what is going on.

Also, if you know the cause of this, or maybe other pages reporting the same behaviour or, I dare hope, a fix, please let me know.

Well, I have been trying to build this control and from day one I had weird issues with the display on Internet Explorer 7. Apparently, because of a bug Rick Strahl reported in his blog, elements that have the position relative escape their containers when the containers themselves are not relative. You will see there a comment from me when I hadn't really understood the problem :(

With the jQuery UI resizable plugin, the base functionality is to change the entire body of the resized control to position relative, causing all kind of trouble, only to permit the resize handles to move around the element (like the south handle having a bottom setting of aproximately 0 px). So, after making all kinds of changes to the javascript in order to solve the IE7 relative position bug, I finally submited and started changing the resizable plugin itself.

The idea was simple: remove position relative, make two divs, one inner and one outer, resize them both in the same time, while another div placed in between would act as the south handle. But it didn't work. I couldn't set an element external to the resized element as the handle, as explained here.

The fix above, though, doesn't entirely show the dimension of the problem. The resizable plugin is incredibly buggy! The documentation says that you can specify custom handles either as jQuery strings or as elements or jQuery objects. That is not correct, as the handles passed as objects are stored in a handles field, but then another _handles field is initialized and the first completely ignored! Also, as in the post above, you need to bind the javascript events to every external element as well, since the original mouse capturing events are placed only on the resized element.

Ok, so the fix is this:
  • look for a this._handles = $('.ui-resizable-handle', this.element).disableSelection(); line. This is where handles is being ignored. Replace it with:
    if (this.handles) {
    var handles=$('nothingReally');
    for (var i in this.handles)
    handles[handles.length++]=this.handles[i][0];
    this._handles=handles;
    } else {
    this._handles = $('.ui-resizable-handle', this.element)
    }
    $.each(this._handles,function() { $(this).disableSelection(); });
  • look for a _mouseInit: function you will see there a line like this.element.bind... you need to add a similar one underneath for all the handles:
    // Add mouse events for the handles as well
    if (this._handles)
    for (var i=0; i<this._handles.length; i++) {
    $(this._handles[i]).bind('mousedown.'+this.widgetName, function(event) {
    return self._mouseDown(event);
    })
    .bind('click.'+this.widgetName, function(event) {
    if(self._preventClickEvent) {
    self._preventClickEvent = false;
    event.stopImmediatePropagation();
    return false;
    }
    });
    }


The change here allows to pass objects (either elements or jQueries) as handles, thus allowing for external elements to act as handles. Removing 'this.element' from the query is not a good idea in case you want to use more resizable controls on the same page. You want only children of a container to act as handles. It could work to move upwards on the control tree until you can get a child that fits the string jquery, but I think that's overkill.

Hope that helps someone.

Update 3rd of March 2016: I've tested for this bug with the latest versions of Internet Explorer, Firefox and Chrome, using the latest jQuery libraries (1.12.1, 2.2.1 and 3.0.0.beta) and it could not be reproduced. The rest of the article may be obsolete.

So I am building this new jQuery based control and I am terribly smug about it until I run the test site on FireFox. Kaboom! Nothing is working. Why? Because FireFox has some issues with the computed style on hidden elements and jQuery people just don't want to fix the problem. But hey, jQuery is open source, right?

So, let's detail the problem. Here is a jQuery bug posting that explains far better than I could what is going on. Apparently, the offsetParent of a hidden element is null in FireFox and the jQuery core function returns the document object when null is given as a parameter [ $(null)==document ]. Then running the FireFox specific function for getting the computed style [ document.defaultView.getComputedStyle(element,null) ] throws an error because the element is now document and it has no style, only its body has.

So, why not fix that? The FireFox error text is '[Exception... "Could not convert JavaScript argument arg 0 [nsIDOMViewCSS.getComputedStyle]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: /jqueryJsFile/ :: anonymous :: line 1349" data: no]'.

The line number might vary with the type of jQuery file version you are using and the amount of modifications you have done to it. What you should find at said line is something like: var computedStyle = defaultView.getComputedStyle(elem, null);.

Solution: Just add above it if (elem == document) elem = document.body; and it solves this particular issue.

In the minifyied version look for var M=q.getComputedStyle(I,null) and add before it if (I==document) I=document.body;


It would be far more elegant to address the problem where the offsetParent is assumed to be not null, but with so many plugins for jQuery, you can't just test them all.

Ever wanted to bind something to the layout rendering phase of an element in Javascript? This helps, by checking at a fixed interval if the size or position of an element have changed and, if so, firing the 'refresh' custom event. All one has to do is then bind to it.

Github page: https://github.com/Siderite/jGenerateRefresh
JQuery plugins page: http://plugins.jquery.com/node/9030

Example:
$(function() { 
$('#target').bind('refresh',{},someRefreshFunction);
$('#target').generateRefreshEvent(100); // every 100 milliseconds
});

In C# 2.0 and above there is this new feature of the '??' double question-mark operator that operates like the SQL isnull function. If x is null then x??y will return: x if it is not null and y if x is null.

A bit annoying, though, that Javascript does not have an operator of the sort. Or so I thought. Enter ||, the logical OR operator. In fact, in javascript x||y will return y if x is null. Also if x is undefined, string empty, 0 or false. But it works in a reasonably similar manner. Beats x===null?y:x anyway.

This is called Short Circuit Evaluation, if you want to be pedantic about it. Be aware that you can chain it, too, similar to a Coalesce function:
0 || null || '' || false || undefined || 'something' // result 'something'