Not so famous, yet powerful feature of absolute positioning is stretching a box. Absolute positioning lets us having a box positioned according to the bounds of the closest relative/absolute/body parent (also known as offset parent).

The most popular use is having a box positioned in either top or bottom and right or left coordinates, and the dimensions of this box are defined by its inner content or a specific width/height.

Example #1 - Absolute Inside Relative, With Fixed Dimensions

“`html
1
2
3
4
5
6
7
8
9
10
11
12
13

```css

.relative {
    position:relative;
    width:100px; height:80px;
    background-color:#6E919A;
}
.absolute {
    position:absolute; top:10px; left:10px;
    width:30px; height:50px;
    background-color:#9BC9D1;
}

But what if you don’t know the dimensions of the parent, or don’t want to maintain the pixels twice on both parent and absolute child?

A height:100% value can be applied only for specific situations: The inner box should be the exact same height as its parent, start at the top and end at the bottom, no offsets. If a margin is applied, the inner box will just be moved but the height will stay the same, hence it will overflow. If a padding is applied, the height of the box will get bigger, and the box will also overflow.

The Solution

The less famous use is to omit width or height of the absolute positioned element and use a combination of top and bottom or left and right, which will cause our box to stretch between the bounds of the offset parent.

Example #2 - Absolute Inside Relative Without a Specific Height: The Absolute Stretches to the Relative’s Bounds

“`html
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
1
2
3
4
5
6
7
8
9
10
11
12
13

```css

.relative {
    position:relative;
    width:100px;
    background-color:#6E919A;
}
.absolute {
    position:absolute; top:10px; bottom:20px; left:10px;
    width:30px;
    background-color:#9BC9D1;
}

What is it Good For?

So many things!

  • If you need 100% width or height for a div but you have padding/border that aren’t counted in the 100%, and therefore the 100% exceeds the parent - use top:0 and bottom:0 with a padding. Example (can be also solved with box-sizing, which isn’t supported by IE8).
  • If you need a designed scroll bar, and it should be as high as its parent’s height, but should also start from a certain offset: top:5px; right:5px; bottom:5px; width:20px; will fix its position. Example.
  • Sticky header and footer, by stretching the content area from header’s end to footer’s start. Example:
“`html
header
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
1

css .header { position:absolute; top:0; left:0; right:0; height:20px; background-color:#6E919A; } .content { position:absolute; top:20px; bottom:20px; right:0; left:0; background-color:#9BC9D1; overflow:auto; } .footer { position:absolute; bottom:0; left:0; right:0; height:20px; background-color:#6E919A; }
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

</div>



<ul>
  <li>If you still can't use border image and other CSS3 goodies, and you have a designed box with image edges - you can use this method to stretch the top/bottom/left/right frame parts, but up to the corners. Example:</li>
</ul>



<div style="display: none;">```html

<div class="relative">
    xxxxx<br/>xxxxx<br/>xxxxx<br/>xxxxx<br/>xxxxx<br/>xxxxx<br/>xxxxx<br/>xxxxx<br/>xxxxx<br/>xxxxx

    <div class="corner left-top"></div>
    <div class="corner right-top"></div>
    <div class="corner left-bottom"></div>
    <div class="corner right-bottom"></div>
    <div class="frame top"></div>
    <div class="frame right"></div>
    <div class="frame bottom"></div>
    <div class="frame left"></div>
</div>?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.relative {
    position:relative;
    width:100px;
    background-color:#6E919A;
    padding:20px;
}
.corner {
    position:absolute;
    width:15px; height:15px; overflow:hidden;
    background-color:#9BC9D1;
}
.corner.left-top { left:0; top:0; }
.corner.right-top { right:0; top:0; }
.corner.left-bottom { left:0; bottom:0; }
.corner.right-bottom { right:0; bottom:0; }

.frame {
    position:absolute; overflow:hidden;
    background-color:#455A5F;
}
.frame.top { height:15px; top:0; right:15px; left:15px; }
.frame.right { width:15px; right:0; top:15px; bottom:15px; }
.frame.bottom { height:15px; bottom:0; left:15px; right:15px; }
.frame.left { width:15px; left:0; top:15px; bottom:15px; }

Share your examples in the comments.

I used to re-save Web.config or Recycle a website in IIS when I wanted to delete all ASP.NET website’s cache / reset all static objects, or basically restart the application.

This piece of code does it, programmatically:

1
HttpRuntime.Close();

So I created a little .ashx/MVC action to do so and access it through the browser.

Have in mind that this will reset the application, including Sessions and static variables, so never use it on production.

I encountered this while uploading a large file to an ASP.NET handler, seems like there’s a default limit of ~30MB for a single request in IIS7 on Windows 7.

After some researching, I found that there’s a setting inside <system.webServer> other than the regular limit in <httpRuntime maxRequestLength=“..”/> (god and MS know why the duplication).

To fix that do one of the following:

Option 1: Add to your Web.config the following code, under the appropriate nodes:

1
2
3
4
5
6
7
<system.webServer>
  <security>
      <requestFiltering>
          <requestLimits maxAllowedContentLength="2147483648" />
      </requestFiltering>
  </security>
</system.webServer>

Option 2: Go to IIS 7 control panel, under your website look for Request Filtering and then Edit features (on the right), then set Maximum allowed content length to your desired limit. This will add to your Web.config the lines from option 1.

Actually I had this while playing with FancyUpload (great thing!) and got Error #2038 on every request.

Definition of the JavaScript this Keyword ? The object which called a function.

The JavaScript this keyword is used within any function scope or the global scope, and in each scope it receives a different value. The value of this inside a function, effectively depends on the object which called it.

What exactly is scope? Every function gets its own space in order to define variables and properties. When we want to access a certain variable, we must do it through the space in which it was defined. In JavaScript, when we haven?t defined a function, everything happens in global scope.

Code

1
2
3
4
5
6
var o={}; // declaring new object
o.name="moon";
o.method=function () {
  alert(this.name);
};
o.method();

We?ve defined a new object named o and a method which displays this.name. But where does this come from?

By calling o.method(), we?ll get the value “moon”. The process that?s taking place is the following:

  1. We create a variable of type string with the value "moon" and assign it to the name property of object o.
  2. We create a function with certain content and assign it as a method of o.
  3. We call the function so that o is the object that calls it.
  4. The function is called when this is actually a reference to o. We get o.name which is "moon".

It is important to note that a function is a variable in every sense. It contains expressions which we can call later on. Having this function assigned to o?s property “method” doesn?t connects the this variable inside it to o. The object doesn?t know about the contents of this function. The actual assignment of this only happens when the function is called, when this is translated as the object that called it, hence, o.

From here, we can make it a slightly more sophisticated:

1
2
3
4
5
6
7
8
9
10
var o={}; // declaring new object
o.name="moon";
o.method=function () {
  alert(this.name);
};

var x={};
x.name="sun";
x.method=o.method;
x.method();

We?ve declared a new object named x with a name property set to “sun”.

We?ve put a reference to the method we defined in o into x.method as well. When calling x.method, we won?t get, god forbid, “moon”, because there is no actual assignment to o. We get “sun” because x is the object that called the function, and the value of this is set to the object which called the function.

We can say that every JavaScript function has a hidden argument named this. Furthermore, with each call to the function, the argument is passed behind the scenes with the pointer to the object which called the function.

1
function f() { alert(this.name); }

Becomes:

1
function f(this) { alert(this.name); }

Meaning:

1
2
3
4
5
6
7
8
9
10
11
12
var o={}; // declaring new object

o.name="moon";
o.method=function (this) {
  alert(this.name);
};
o.method(o);

var x={};
x.name="sun";
x.method=o.method;
x.method(x);

In C++, the compiler adds an argument named this to every method in a class, which is an object of the class type, and effectively every call to a method becomes a call to the method together with that variable (please ignore C++ wrong syntax):

1
2
3
4
5
6
7
class Foo {
  string name="foo";
  string GetName() { return this.name; }
}

Foo o=new Foo();
string s=o.GetName();

Actually becomes something like:

1
2
3
4
5
6
7
class Foo {
  string name="foo";
  string GetName(Foo this) { return this.name; }
}

Foo o=new Foo();
string s=o.GetName(o);

More on this in C++ on Wikipedia

Changing the Value of this

It is possible to change the value of this, not by assignment (you cannot assign a value to this), but rather by calling a function via another object, as we did with x ? defining the function as a property of an object and calling the function through it.

JavaScript gives us the tools to call a function with a different this without too much effort, with the help of the methods call and apply. These two methods are quite similar: they are methods of a function (defined in Function.prototype) that take an object that should be the this and arguments, and call the function itself with these arguments. The difference is in how the arguments are passed ? call takes regular arguments (like params in C#), and apply takes the arguments as an array.

We?ll change the former code to work with call:

1
2
3
4
5
6
7
8
var o={}; // declaring new object
o.name="moon";
o.method=function () {
  alert(this.name);
};
var x={};
x.name="sun";
o.method.call(x);

What happens behind the scenes, sort of:

1
2
x.temporaryMethod=o.method;
x.temporaryMethod();

this and new Operators

A JavaScript function is not just a group of statements for later use, it also serves as a class; every function is also a class. We can create instances of a class.

1
2
3
function Foo(name) {
  this.name=name;
}

This function, like all functions, is also a class; we create an instance of it thus:

1
2
var instance=new Foo("bar");
alert(instance.name); // "bar"

What is actually happening behind the scenes? When we call new Foo(“bar”):

1
2
var instance={}; // declaring new, empty object
Foo.call(instance,name); // calling the constructor with the new object as this, and the argument "name"

Calling the constructor will call the expression:

1
this.name=name; // this is the "instance" object. assign name as the sent argument

The compiler creates a new, empty object and activates the class? constructor with call. This way, this will be a reference to the newly created object. The constructor calls the expressions and the references to this that it contains, and then new object is returned.

this and prototype

The prototype property is a class property, and whichever value we assign it will be available to all instances of the class. When accessing an object property, the existence of the property in the object will be checked first and, if not found, will be checked in the prototype of the class to which the object belongs (with Object being the basic class).

In JavaScript there are a number of pre-defined classes:

1
2
3
4
5
6
7
8
Object
Function
String
Number
Array
Date
Error
RegExp

We can extend any class with our own functions, and so each instance of the class will contain our extension.

C# contains a feature called extension method which extends the functionality of built-in classes such as int and string. This feature is also found in Ruby.

1
2
3
4
5
6
String.prototype.trim=function () {
  return this.replace(/^\s+|\s+$/g,"");
};
var s="&nbsp;&nbsp;&nbsp; x&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ";
alert("<"+s+">");
alert("<"+s.trim()+">");

After extending the prototype of the class String with a property named trim which is a function that trims blank spaces from the beginning and end of the string, we can access this method from any string. this in the function will contain the value of the string, because the string variable is the object that called the function.

this and the DOM

1
<div id="div" onclick="alert(this.innerHTML);">div</div>

The DOM knows to interpret the code thus:

1
2
3
div.onclick=function () {
  alert(this.innerHTML);
};

From here it looks familiar; onclick is defined as a property whose value is a function with use of this.

The browser will apply a ?listener? for mouse clicks. Once a click is received, it checks whether its location is on this div. If so, it checks whether the div has an onclick attribute, and then just calls the function like this:

1
div.onclick(event);

Thus, this contains a reference to the div.

Summary

this is a wide world in JavaScript. Comprehensive understanding of it will allow us to write shorter, more efficient and advanced code.

When you plan to apply a big change to a database table, you should always triple check your queries, so nothing will get screwed.

I always use the following approach, in order to preview data before and after a change that’s going to be made over records without having this change committed, so I can refine my queries if I did something wrong:

MySQL

1
2
3
4
5
6
7
8
9
10
11
12
13
START TRANSACTION;

-- select the data before change
SELECT * FROM table_name WHERE some_id=5;

-- change the data
UPDATE table_name SET quantity=quantity+1 WHERE some_id=5;

-- select the data after change, and see if everything went alright
SELECT * FROM table_name WHERE some_id=5;

-- undo the change
ROLLBACK;

SQL Server

1
2
3
4
5
6
7
8
9
10
11
12
13
BEGIN TRAN;

-- select the data before change
SELECT * FROM table_name WHERE some_id=5;

-- change the data
UPDATE table_name SET quantity=quantity+1 WHERE some_id=5;

-- select the data after change, and see if everything went alright
SELECT * FROM table_name WHERE some_id=5;

-- undo the change
ROLLBACK TRAN;

Description

  1. A transaction is opened
  2. All current rows are selected, to preview data before change
  3. The change is being done
  4. All altered rows are selected, to preview data after change
  5. The transaction is rollbacked, the change is undone

After you’re sure the change is OK, you can perform it without a transaction, or use COMMIT; (MySQL) / COMMIT TRAN (SQL Server).

(Script also on GitHub and MooTools Forge)

It’s great to track all of your classes’ instances for debugging purposes or mass altering.

Huh? Mass Altering?

  • For instances of some Audio/Video player classes: stop/pause all players
  • For instances of positioned elements: recalculate position of all elements upon window resize
  • Call hide method of all instances of a class upon an event

I needed it more than once and I used to track instances from within any class I needed it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var MyClass=new Class({
  initialize:function () {
      MyClass.instances.push(this);
  },
  recalcPosition:function () {
      // something that recalculates position or any other task that should happen on all instances
  }
});

MyClass.instances=[];

// from another code:
MyClass.instances.each(function (instance) {
  instance.recalcPosition();
});

However, I got too many classes with this behavior. I ended up writing a MooTools Class Mutator to automate the process:

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
/*
---

script: Class.Mutators.TrackInstances.js

description: Allows a class to track its instances by having instances array as a class property

license: MIT-style license

authors:
- Elad Ossadon ( http://devign.me | http://twitter.com/elado )

requires:
- core:1.2.4

provides: [Class.Mutators.TrackInstances]

...
*/

Class.Mutators.TrackInstances=function (allow) {
  if (!allow) return;

  // save current initialize method
  var oldInit=this.prototype.initialize;
  var klass=this;

  // overwrite initialize method
  klass.prototype.initialize=function () {
      (klass.instances=klass.instances || []).push(this);
      oldInit.apply(this,arguments);
  };
};

Usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var MyClass=new Class({
  initialize:function () {
  },

  TrackInstances:true,

  recalcPosition:function () {
      // something that recalculates position or any other task that should happen on all instances
  }
});

var x=new MyClass();
var y=new MyClass();

MyClass.instances; // [x, y]
MyClass.instances.length; // 2

// from another code:
window.addEvent("resize",function () {
  MyClass.instances.each(function (instance) {
      instance.recalcPosition();
  });
});

The only constraint is that the “initialize” declaration in an object should be prior to the TrackInstances:true. That’s because mutators are called in the same loop as all other methods, and if the loop didn’t get to a certain method, then the mutator won’t know it. According to these tickets, the MooTools team won’t fix it anytime soon.

Yes. I know I should never rely on for..in loop order, but when it comes to inconsistency of browsers it can be annoying.

I found it out when I wanted to fetch the first key of an object, but got different results on chrome (incorrect result) and other browsers.

Code:

1
2
3
4
5
6
7
8
9
10
11
console.log("wordsAsKeys");
var wordsAsKeys={ words:"value",as:"value",keys:"value" };
for (var k in wordsAsKeys) console.log(k);

console.log("numbersAsKeys");
var numbersAsKeys={ "3":"value","2":"value","1":"value" };
for (var k in numbersAsKeys) console.log(k);

console.log("mixedKeys");
var mixedKeys={ "3":"value",words:"value","1":"value" };
for (var k in mixedKeys) console.log(k);

The Result:

Firefox / Safari / IE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
wordsAsKeys
  words
  as
  keys

numbersAsKeys
  3
  2
  1

mixedKeys
  3
  words
  1

Chrome:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
wordsAsKeys
  words
  as
  keys

numbersAsKeys
  1
  2
  3

mixedKeys
  1
  3
  words

As you can see, the second and third loops enumerate on an object with numbers as indexes. What Google Chrome seem to do is treat the object as an Array, which outputs the numeric indexes first, in ascending order.

To me, it looks like a bug that may create inconsistency. Google & Chromium team - please fix it :)