Search

12/30/2007

premature optimization is the root of all evil

Optimization (computer science) - Wikipedia, the free encyclopedia

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
(Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.)
"Premature optimization" is a phrase used to describe a situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.

Cook Computing : Premature Optimization
Its usually not worth spending a lot of time micro-optimizing code before its obvious where the performance bottlenecks are. But, conversely, when designing software at a system level, performance issues should always be considered from the beginning. A good software developer will do this automatically, having developed a feel for where performance issues will cause problems. An inexperienced developer will not bother, misguidedly believing that a bit of fine tuning at a later stage will fix any problems.

12/28/2007

Jash: JavaScript Shell

Jash: JavaScript Shell
Documentation
Firefox上面已經有firebug了, 所以這個東西還是用IE上面比較適合

Jash is a DHTML-based window that gives you command-line JavaScript access to the current browser window. With this console you can quickly debug scripts, manipulate the DOM, view the current page's objects, functions, and variables, trace the execution stack, execute arbitrary Javascript, enter new CSS (in IE, Firefox, Opera, and Safari), and much more.

substring


s = 'http://forum.pcdvd.com.tw/search.php?searchid=7218092&pp=25&page=11'

//find string from 'searchid='
s.substring(s.indexOf('searchid='))
//"searchid=7218092&pp=25&page=11"
s.substring(0, s.indexOf('searchid='))
//"http://forum.pcdvd.com.tw/search.php?"

//find string from 'searchid=' but not include 'searchid='
s.substring(s.indexOf('searchid=') + ('searchid=').length)
//"7218092&pp=25&page=11"

reStructuredText

reStructuredText

reStructuredText is an easy-to-read, what-you-see-is-what-you-get plaintext markup syntax and parser system. It is useful for in-line program documentation (such as Python docstrings), for quickly creating simple web pages, and for standalone documents. reStructuredText is designed for extensibility for specific application domains. The reStructuredText parser is a component of Docutils. reStructuredText is a revision and reinterpretation of the StructuredText and Setext lightweight markup systems.

Cross Domain Frame Communication

Julien Lecomte’s Blog » Introducing CrossFrame, a Safe Communication Mechanism Across Documents and Across Domains
Tagneto: Cross Domain Frame Communication with Fragment Identifiers (for Comet?)

JavaScript and Object Oriented Programming (OOP)

JavaScript and Object Oriented Programming (OOP)
An object constructor is merely a regular JavaScript function, so it's just as robust (ie: define parameters, call other functions etc). The difference between the two is that a constructor function is called via the new operator

function cat(name) {
this.name = name;
this.talk = function() {
alert( this.name + " say meeow!" )
}
}

cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"

cat2 = new cat("ginger")
cat2.talk() //alerts "ginger says meeow!"

We use it when we would like an object to inherit a method after it has been defined. Think of prototyping mentally as "attaching" a method to an object after it's been defined, in which all object instances then instantly share.
cat.prototype.changeName = function(name) {
this.name = name;
}

firstCat = new cat("pursur")
firstCat.changeName("Bill")
firstCat.talk() //alerts "Bill says meeow!"

JavaScript supports prototype inheritance instead of class based. It's possible for inheritance to happen other ways, however.
function superClass() {
this.supertest = superTest; //attach method superTest
}

function subClass() {
this.inheritFrom = superClass;
this.inheritFrom();
this.subtest = subTest; //attach method subTest
}

function superTest() {
return "superTest";
}

function subTest() {
return "subTest";
}


var newClass = new subClass();

alert(newClass.subtest()); // yields "subTest"
alert(newClass.supertest()); // yields "superTest"

javascript access control: private variables

lixo.org :: JavaScript: Put everything in a namespace


var Article = Article ? Article : new Object();
Article.title = “Report: School Shootings Help Prepare Students For Being Shot In Real World”;
Article.save = function() {
alert(”Saving ” + this.title);
}

use the object literal notation directly:


var Article = Article ? Article : {
title: “Report: School Shootings Help Prepare Students For Being Shot In Real World”,
save: function() {
alert(”Saving ” + this.title)
}
}

These two last examples are great if you’re not that concerned about exposing the ‘title’ attribute to the rest of the world. If there is a chance that problems could arise if some other piece of code changed it directly, there is a solution:

var Article = Article ? Article : function() {
var private = {
title: “Report: School Shootings Help Prepare Students For Being Shot In Real World”
};

var public = {
getTitle: function() {
return private.title;
},

save: function() {
alert(”Saving ” + this.getTitle());
}
}

return public;
}();

by creating an anonymous function that returns the object I want to define, and then immediately calling it (note the ‘()’ at the last line), I can hide whatever I don’t want other parts of the code to see - it’s all tucked away in the local context of that anonymous function.

12/27/2007

MyEnTunnel - A background SSH tunnel daemon

MyEnTunnel - A background SSH tunnel daemon

MyEnTunnel is a simple system tray application (or NT service) that establishes and maintains TCP SSH tunnels. It does this by launching Plink (PuTTY Link) in the background and then monitors the process. If the Plink process dies (e.g. connection drops, server restarts or otherwise becomes unreachable) MyEnTunnel will automatically restart Plink to reestablish the tunnels in the background. It tries to use as little CPU and system resources as possible when monitoring (When the "Slow Polling" option is enabled it only does one context switch per second).

<META http-equiv imagetoolbar>


<META HTTP-EQUIV="imagetoolbar" CONTENT="no">

Indicates that the toolbar is not to be shown for all images on the page.

Dean Edwards: Using Google To Serve Faster JavaScript

Dean Edwards: Using Google To Serve Faster JavaScript - free static file hosting & svn version control & wiki document, what could be better?
http://code.google.com/p/deanedwards/
http://deanedwards.googlecode.com/svn/trunk/
用 Google Code 放 Javascript… at Gea-Suan Lin’s BLOG
Update: http://chunghe.googlecode.com/svn/trunk/
修改mime type的方法: HowToBuild - flexlib - Google Code


update: WikiSyntax - support - Google Code
tag: subversion config

scripting select and option

http://chunghe.googlepages.com/select.htm
在select中選擇發生的事件是 onchange, foo.selectedIndex 可以抓到選取項目的 index, 從 0 開始, foo.options[foo.selectedIndex]可以抓取項目的 reference, foo.options[foo.selectedIndex].value可以抓到選取項目的 value, bar.options[i].selected = true 可以選取第 i 項 option

var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var mapping = {
'programming': 'a',
'surfing' : 'd',
'caffeine' : 'b',
'annoying_ohoh' : 'c',
'thinking' : 'x'
}
foo.onchange = function(){
// get the value of selected item
var selectedValue = foo.options[foo.selectedIndex].value;
if('undefined' === typeof mapping[selectedValue]){
alert(selectedValue + ': no such item');
return
}

// map the select value to another select
var mappingValue = mapping[selectedValue];

// search select 'bar' for the mappingValue
var options = bar.getElementsByTagName('option');
for(var i=0; i<options.length; i++){
if(options[i].value == mappingValue){
bar.options[i].selected = true;
break;
}
}
if(options.length == i){
alert(foo.options[foo.selectedIndex].value + ': no match');
}
}

12/26/2007

location.search & get query string

//location.href
"http://www.example.com/foo.php?userid=someone&book=7"
//location.search
"?userid=someone&book=7"
//location.search.indexOf(1)
"userid=someone&book=7"

/*
* This function parses ampersand-separated name=value argument pairs from
* the query string of the URL. It stores the name=value pairs in
* properties of an object and returns that object. Use it like this:
*
* var args = getArgs( ); // Parse args from URL
* var q = args.q || ""; // Use argument, if defined, or a default value
* var n = args.n ? parseInt(args.n) : 10;
*/
function getArgs( ) {
var args = new Object( );
var query = location.search.substring(1); // Get query string
var pairs = query.split("&"); // Break at ampersand
for(var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('='); // Look for "name=value"
if (pos == -1) continue; // If not found, skip
var argname = pairs[i].substring(0,pos); // Extract the name
var value = pairs[i].substring(pos+1); // Extract the value
value = decodeURIComponent(value); // Decode it, if needed
args[argname] = value; // Store as a property
}
return args; // Return the object
}

12/25/2007

syntaxhighlighter

終於有syntax highlighting了, powered by syntaxhighlighter - Google Code, 色調是vim desert theme, code 直接看source就有了,http://chunghe.googlepages.com/shCoreJsCss.js Blogger的使用者要看這篇 BloggerMode - syntaxhighlighter - Google Code

dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');

Update: G牌的google-code-prettify

無限猴子定理 - Wikipedia

無限猴子定理 - Wikipedia
Infinite monkey theorem - Wikipedia, the free encyclopedia

無限猴子定理說明,一隻猴子隨機在打字機鍵盤上按鍵,最後必然可以打出法國國家圖書館中的每本書。

OPML (Outline Processor Markup Language)

OPML - Wikipedia, the free encyclopedia - bloglines 可以匯出 OPML 格式的 feeds list 給 google reader吃

OPML (Outline Processor Markup Language) is an XML format for outlines. Originally developed by Radio UserLand as a native file format for an outliner application, it has since been adopted for other uses, the most common being to exchange lists of web feeds between web feed aggregators.

The OPML specification defines an outline as a hierarchical, ordered list of arbitrary elements. The specification is fairly open which makes it suitable for many types of list data.

prototype wrapper for YUI Dom utilities

http://chunghe.googlepages.com/prototype.wrapper.for.YUI.Dom.utilit.htm
用prototype把常用的一些 YUI Dom utilities (getRegion, getXY, getViewportHeight/getViewportWidth, getDocumentScrollTop/getDocumentScrollLeft)重寫一次,還是比較習慣YUI的naming convention,順便熟悉一下在prototype的哪些function mapping到YUI的哪些function。
值得一提的是 document.viewport.getDimensions().width;這個會把viewport width多算'17px',之前在lightbox.js也有遇到一樣的問題,不是很確定,所以用了YUI的code把這部分補起來。另外YUI在IE底下,getXY在X與Y都多算了'2px',prototype算起來倒是正確的。

var PUD = {
getXY: function(ele){
var ele = $(ele);
var pos = ele.positionedOffset();
return [pos.left, pos.top];
},

getRegion: function(ele){
var ele = $(ele);
var pos = ele.positionedOffset();
var t = pos[1];
var r = pos[0] + ele.offsetWidth;
var b = pos[1] + ele.offsetHeight;
var l = pos[0];
return [t, r, b, l];
},

getViewportHeight: function(ele){
return document.viewport.getDimensions().height;
},

getWrongViewportWidth : function(ele){
// belowing method provided by prototype has '17px' margin error
return document.viewport.getDimensions().width;
},

getViewportWidth : function(ele){
// belowing method provided by prototype has '17px' margin error
//return document.viewport.getDimensions().width;
var width = self.innerWidth;
var mode = document.compatMode;

if (mode || Prototype.Browser.IE) { // IE, Gecko, Opera
width = (mode == 'CSS1Compat') ?
document.documentElement.clientWidth : // Standards
document.body.clientWidth; // Quirks
}
return width;
},

getDocumentScrollLeft : function(ele){
return document.viewport.getScrollOffsets()[0];
},

getDocumentScrollTop : function(ele){
return document.viewport.getScrollOffsets()[1];
}
}

12/24/2007

CSS filters vs. conditional comment

css.filters
centricle : css filters (css hacks) - 非常詳細的列出各式樣的 css hacks & filters 以及在不同的 browsers & OSs 下面的情形。

                ie7 ie6
* html div N Y
_property:value Y Y
*property:value N Y

MSDN - About Conditional Comments
Hack-free CSS for IE - Arve Bersvendsen
<link rel="stylesheet" type="text/css" href="common.css" />

<!--[if IE]>
<link rel="stylesheet" type="text/css" href="all-ie.css" />
<![endif]-->

<!--[if IE 6]>
<link rel="stylesheet" type="text/css" href="ie-6.0.css" />
<![endif]-->

<!--[if IE lt 6]>
<link rel="stylesheet" type="text/css" href="ie-5.0+5.5.css" />
<![endif]-->

Mastering JavaScript — concept and resource guide

Mastering JavaScript — concept and resource guide » d’bug - here's a list of advanced javascript.
Access Control
* Private Members in JavaScript
* How to achieve private, public, and privileged members in JavaScript
* Private JavaScript
Closures
* JavaScript Closures for Dummies
* JavaScript Closures
* Closures and executing JavaScript on page load
Classical OOP
* JavaScript Object-Oriented Programming Part 1
* Objectifying JavaScript
* JavaScript and Object Oriented Programming (OOP)
* Douglas Crockford Video: Advanced JavaScript
Namespaces and Self-invoking Functions
* Namespacing your JavaScript
* JavaScript Namespaces
* JavaScript: Put everything in a namespace
Concepts in AJAX
* AJAX Queue Class
* Reusing XMLHttpRequest Object in IE
* AJAX Patterns
* Managing sessions in an Ajax-enabled application

Internet Explorer box model bug

Internet Explorer box model bug - Wikipedia, the free encyclopedia
務必記住用 YUI: YAHOO.util.Dom.getRegion 算出來的 height/width 是整個 box 的 高度/寬度, 也就是包含 padding, border 但不包含 margin

Internet Explorer versions 6 and 7 are not affected by the bug if the page contains certain HTML document type declarations. These versions maintain the buggy behavior when in quirks mode for reasons of backward compatibility.[4] For example, quirks mode is triggered:
* When the document type declaration is absent or incomplete;
* When an HTML 3 or earlier document is encountered;
* When an HTML 4.0 Transitional or Frameset document type declaration is used and a system identifier (URI) is not present;
* When an SGML comment or other unrecognized content appears before the document type declaration, or if there are errors elsewhere in the document;
* Internet Explorer 6 also uses quirks mode if there is an XML declaration prior to the document type declaration.[5]
Box model hacks have proven unreliable because they rely on bugs in browsers' CSS support that may be fixed in later versions. For this reason, some Web developers have instead recommended either avoiding specifying both width and padding for the same element or using conditional comments to work around the box model bug in older versions of Internet Explorer.[6][7]

12/23/2007

How to Win Friends & Influence People

女工程師的紐約生活手札 - "You Speak Good English." "Thank You!"
Amazon.com: How to Win Friends & Influence People: Books: Dale Carnegie

第一章講不要批評抱怨,第二章強調稱讚的重要性。裡面搭配很多政治人物、名人、成功企業家遇到衝突的狀況與如何以智慧的言語化解危機與贏得人心。原來美國這種講話著重稱讚的哲學是其來有自的,書上提到的政治人物、商場企業家都知道要成為成功領導者,通常並不是最有能力的者,而是那個可以有效溝通想法並影響、啟發、說服他人與自己一起朝目標前進的人。而要讓對方能照自己的意思去作,當中很重要的是了解對方的想法,而首當其衝的是誠心的稱讚。每個人都想要追求”A feeling of importance”,能適時誠心的稱讚你的伴侶、小孩、親人、員工、朋友等,不但可以免除很多衝突、不滿、仇恨的情緒,真誠的稱讚也將在對方的腦中如美妙的音樂般,盤旋許久。

12/21/2007

The YUI CSS Foundation

Nate Koechley: "The YUI CSS Foundation&quo - Yahoo! Video
components

  • Reset - a clean foundation(把所有的樣式取消, 包含h1-h6都同樣size, em.strong的效果也都取消.)
  • Fonts - typographical control-> for free(1)arial (2)13px font size (3)16px line height
  • Grids - layout and page control
  • Base - basic helper/snippets lib (把Reset取消的code放回來, 如果要自己design style, 就不需要include這支, 因為production的css會蓋過Base蓋過Reset不太make sense)
fonts.css (font.css在IE下可以改變字型大小的原因是因為apply到後面的*font-size:small & *font:x-small而不是前面的13px)
body {font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;}
table {font-size:inherit;font:100%;}
de,kbd,samp,tt {font-family:monospace;*font-size:108%;line-height:100%;}

grid.css
1. 決定total page width,有下面五種 doc width
(1)#doc 750px, (2)#doc2 950px, (3)#doc3 100%, (4)#doc4 974px, (5)#doc-custom
#doc-custom的作法(1) 決定寬度: ex: 650px (2) 除以13: 46.15em (3) 乘上0.9759: 45.04 em
#custom-doc{
margin:auto;
text-align: left;
width: 46.15em;
*width: 45.04em;
min-width: 600px; /* not necessary but recommanded */
}

2. 決定邊欄的位置&寬度,有以下6種template
(1).yui-t1: 160 left, (2).yui-t2: 180 left, (3).yui-t3 300 left, (4).yui-t4 180 right, (5).yui-t5 240 right, (6).yui-t6 300 right
Two content blocks: yui-b for blocks, 一個是比較寬的main,另一個是比較窄的的邊欄
<div id="doc">
<div class="yui-b"></div>
<div class="yui-b"></div>
</div>

把主要的main用yui-main包起來: identify the main block:
<div id="doc">
<div id="yui-main">
<div class="yui-b"></div>
</div>
<div class="yui-b"></div>
</div>

所以整個結構變成
<div id="doc" class="yui-t3">
<div id="hd"></div>
<div id="bd">
<div id="yui-main">
<div class="yui-b"></div>
</div>
<div class="yui-b"></div>
</div>
<div id="ft"></div>
</div>

3. 建立grid: 第一個yui-u or yui-g要多一個class 'first',用來決定float方向
.yui-g: grid holder
.yui-u: grid units
兩個column,各佔50%
<div class="yui-g">
<div class="yui-u"></div>
<div class="yui-u"></div>
</div>

四個column,各佔25%
<div class="yui-g">
<div class="yui-g first">
<div class="yui-u" first>
<div class="yui-u">
</div>
<div class="yui-g">
<div class="yui-u" first>
<div class="yui-u">
</div>
</div>

uneven grid holder
.yui-gb 1/3 1/3 1/3
.yui-gc 2/3 1/3
.yui-gd 1/3 2/3
.yui ge 3/4 1/4
.yui-gf 1/4 3/4

review
1. Page width: div #doc
2. Templates: .yui-t1
3. Grids: .yui-g .yui-u
4. Fills all space
5. Nestable & stackable

quote

只有两种计算机语言:一些语言天天挨骂,另外一些没有人用。(Bjarne Stroustrup)

http://www.example.com

You have reached this web page by typing "example.com", "example.net", or "example.org" into your web browser.

These domain names are reserved for use in documentation and are not available for registration. See RFC 2606, Section 3.

12/20/2007

when inline css is useful

http://developer.yahoo.com/yui/examples/container/overlay.html

The markup for overlay1, plus the context element ctx and the buttons to show all our Overlays, is displayed below. Note that overlay1 has an inline style of visibility:hidden set in advance. Most browsers are slower to render CSS than inline styles, and we want this marked-up Overlay to be hidden by default. If the inline style isn't present, it may cause a brief "flash of unstyled content" where the Overlay may be visible on slower machines.

比薩塔 Pizza Top:簡約的豐富生活:Xuite日誌

比薩塔 Pizza Top:簡約的豐富生活:Xuite日誌
比薩塔 Pizza Top
台北市金華街181號1樓
(02)2327-8028、23278208
這裡的消費採吃到飽的方式,平日中午(11:00~16:30)220元加一成,晚餐及假日250加一成,都是現烤供應吃到飽

yui useful functions

YAHOO.lang.dump

 var t = {
'who': 'foo',
'email': 'foo@example.com',
'c': function(){
alert( 'who:' + this.who + ' email:' + this.email )
}
}
alert(YAHOO.lang.dump(t));
//{who => foo, email => foo@example.com, c => f(){...}}

YAHOO.lang.trim
Returns a string without any leading or trailing whitespace. If the input is not a string, the input will be returned untouched.

 var t = '  example string  ';
YAHOO.lang.trim(t);
alert('|' + t + '|');
alert('|'+ YAHOO.lang.trim(t) + '|');
//| example string |
//|example string|

12/19/2007

Ajaxian » Unobtrusively Mapping Microformats with jQuery

Ajaxian » Unobtrusively Mapping Microformats with jQuery - jQuery寫起來真好看
最後的成品

Simon puts together jQuery, microformats, and the Google Maps API to grok hCard and show maps of any hCard data that is found, ending up with:
jQuery('.vcard').each(function() {
var hcard = jQuery(this);
var streetaddress = hcard.find('.street-address').text();
var postcode = hcard.find('.postal-code').text();
var geocoder = new MapstractionGeocoder(function(result) {
var marker = new Marker(result.point);
marker.setInfoBubble(
'<div class="bubble">' + hcard.html() + '</div>'
);
mapstraction.addMarker(marker);
}, 'google');
geocoder.geocode({'address': streetaddress + ', ' + postcode});
});

Computed vs Cascaded Style

Computed vs Cascaded Style

function getStyle(el, prop) {
if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el, null)[prop];
} else if (el.currentStyle) {
return el.currentStyle[prop];
} else {
return el.style[prop];
}
}

So what is wrong with this you might ask?.

div { width: 500px; font-size: 12px; }
p { width: 50%; font-size: 1em; }
a { font-size: inherit; }

<div>
<p id="p">Some text with <a id=a href=#>a link</a>.
More <b style="font-size:150%">text</b></p>
</div>


alert(getStyle(document.getElementById('p'), 'fontSize'));
//ie:1em(cascaded style) ff: 12px(computed style)

alert(getStyle(document.getElementById('p'), 'width'));
//ie:50%(cascaded style) ff:250px(computed style)

All browsers except IE has a way to get the computed style. The way to do
this is to use document.defaultView.getComputedStyle. Only IE has a way to get
the cascaded style. This is done using element.currentStyle.

12/18/2007

The Django Book

The Django Book - great online django book. The comment system is cool as well.
official django tutorial
update: Django pronunciation
update: The Django Book: Version 2.0

12/17/2007

TrueCrypt

TrueCrypt - Free Open-Source On-The-Fly Disk Encryption Software for Windows Vista/XP/2000 and Linux
Free open-source disk encryption software for Windows Vista/XP/2000 and Linux

Main Features:
* Creates a virtual encrypted disk within a file and mounts it as a real disk.
* Encrypts an entire hard disk partition or a storage device such as USB flash drive.
* Encryption is automatic, real-time (on-the-fly) and transparent.
* Provides two levels of plausible deniability, in case an adversary forces you to reveal the password:
1) Hidden volume (steganography – more information may be found here).
2) No TrueCrypt volume can be identified (volumes cannot be distinguished from random data).
* Encryption algorithms: AES-256, Serpent, and Twofish. Mode of operation: LRW.
Further information regarding features of the software may be found in the documentation.

12/10/2007

pre-wrap equivalent

IE/win Expanding Box
Stopping long words destroying layout

Contrary to spec, IE allows very long words to expand a box widthwards - which can then easily destroy a layout if other boxes are floated right.
Add this rule to the box that holds blog comments (or do what I did, and just add it to the body tag):
body {word-wrap: break-word;}

white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */

<nobr> equivalent
.nowrap { white-space: nowrap; }

yui code snippet

The Yahoo! User Interface Library. Simon Willison. XTech Ajax Developer’s Day
Preparatory notes for "The Yahoo! User Interface Library" at XTech
getElementsBy which is more general, taking an acceptance function that is passed each node in turn and must return true or false:

YAHOO.util.Dom.getElementsBy(function(el) {
return (/^http:\/\/www\.yahoo\.com/.test(el.getAttribute('href')));
}));

YAHOO.util.Connect.asyncRequest(
'GET', '/ajaxy-goodness', {
success: function(o) {
alert(o.responseText);
},
failure: function(o) {
alert('Request failed: ' +o.statusText);
}
}
);

As you can see, you pass in an object containing success and failure callback functions. The connection object can also handle scope correction, for example if you want to call methods on a JavaScript object:

YAHOO.util.Connect.asyncRequest('GET', '/ajaxy-goodness', {
success: myObject.onSuccess,
failure: myObject.onFailure,
scope: myObject
});

Custom Event
var myEvent = new YAHOO.util.CustomEvent(
'myEvent'
);
myEvent.subscribe(function() {
alert('event fired');
});
myEvent.fire();


function onSuccess(o) {
alert(o.argument);
}

YAHOO.util.Connect.asyncRequest('GET', '/ajaxy-goodness', {
success: onSuccess,
argument: 'some extra data'
});

onavailable
YAHOO.util.Event.onAvailable(
'mydiv', function() {
alert('mydiv has become available');
}
);

Extra callback arguments
function msgAlert(e, msg) {
alert(msg);
}
YAHOO.util.Event.on(
'mydiv', 'click', msgAlert, "My div was clicked"
);

Reference:
Preparatory notes for "The Yahoo! User Interface Library" at XTech

How to make Ajax work for you

How to make Ajax work for you » SlideShare - simple & clear AJAX codes
How to make Ajax work for you

var xhr = createXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert(xhr.responseText);
} else {
alert('Error code ' + xhr.status);
}
}
};
xhr.open('GET', '/helloworld.txt', true);
xhr.send(null);

function createXHR() {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
return xhr;
}

var xhr = createXHR();
xhr.onreadystatechange = onComplete;
xhr.open('POST', '/helloworld.php', true);
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
xhr.send('name=Simon&age=26');

xhr.open('POST', '/helloworld.php', true);
The third argument specifies that we want to make an asynchronous request (“tell me when you’re done by calling this function”). If you set this to false you’ll get a synchronous request, which will completely hang the browser until the request returns. Don’t do that.

function buildQueryString(obj) {
var bits = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
bits[bits.length] = escape(key) + '=' +
escape(obj[key]);
}
}
return bits.join('&');
}
var s = buildQueryString({
name: 'Simon',
age: 26
});
name=Simon&age=26

There's still a complete doRequest function. Keep reading ...
<form id="evil" action="http://example.com/admin/delete.php" method="POST">
<input type="hidden" name="id" value="5">
</form>
<script>
document.getElementById('evil').submit()
</script>

Unobtrusive Javascript、Progressive Enhancement、Gracefully Degrade

从几个与 DOM 脚本编程有关的术语翻译说起

为了给用户更佳的体验,我想做到 Progressive Enhancement。然而,要是人家浏览器不支持怎么办?好吧,那就 Gracefully Degrade 吧。换句话说,Progressive Enhancement 是代表美好理想的新体验,而 Gracefully Degrade 则是面对残酷现实的替代品。

Unobtrusive Javascript
From DHTML to DOM scripting - an example of how to replace outdated JavaScript techniques.

12/09/2007

How to Answer Behavioral Interview Questions

How to Answer Behavioral Interview Questions
Complete List of Behavioral Interview Questions

DOM/JavaScript famous person


Brendan Eich - creator of JavaScript
Blog: Brendan's Roadmap Updates




Chris Heilmann
著作: 《Beginning JavaScript with DOM Scripting and Ajax》
BLOG: Wait till I come!
From DHTML to DOM Scripting



著作: 《DOM Scripting》
Jeremy Keith



Dustin Diaz - founder of CSS Naked Day
著作: 《Pro JavaScript Design Patterns》
Blog: Dustin Diaz: ./with Imagination

12/07/2007

Google Chart API

Developer's Guide - Google Chart API - Google Code - 圖比excel的好看


Mr./Ms. Days (MMDays) - 網路, 資訊, 觀察, 生活 » Blog Archive » 用網址畫圖,Google 推出 Google Chart API
unofficial google rounded corner api
Charts And Graphs: Modern Solutions | Developer's Toolbox | Smashing Magazine
update: there are many tools generating charts visually
Chart Maker - Generator for the Chart Server API
Online Charts Builder
update:
這邊有人寫了一個簡單的proxy把request cache起來
Wait till I come! » Blog Archive » Generating charts from accessible data tables and vice versa using the Google Charts API

Understanding and Solving Internet Explorer Leak Patterns

The problem with innerHTML
Understanding and Solving Internet Explorer Leak Patterns

1. Circular References—When mutual references are counted between Internet Explorer's COM infrastructure and any scripting engine, objects can leak memory. This is the broadest pattern.
2. Closures—Closures are a specific form of circular reference that pose the largest pattern to existing Web application architectures. Closures are easy to spot because they rely on a specific language keyword and can be searched for generically.
3. Cross-Page Leaks—Cross-page leaks are often very small leaks of internal book-keeping objects as you move from site to site. We'll examine the DOM Insertion Order issue, along with a workaround that shows how small changes to your code can prevent the creation of these book-keeping objects.
4. Pseudo-Leaks—These aren't really leaks, but can be extremely annoying if you don't understand where your memory is going. We'll examine the script element rewriting and how it appears to leak quite a bit of memory, when it is really performing as required.

IEBlog : Tools for Detecting Memory Leaks
Drip and sIEve
GPDE Team Blog : JavaScript Memory Leak Detector (v2)
Via: Tsung's Blog | IE 偵測 Memory Leaks 的程式

12/06/2007

microformat & Tails Export :: Firefox Add-ons

Tails Export :: Firefox Add-ons
Operator :: Firefox Add-ons

An extension for Showing and Exporting Microformats.

Can Your
Website be Your API? — All in the head
http://microformats.org/blog/2007/06/21/microformatsorg-turns-2/
First hCard profile import implemented! Mere days ago, Satisfaction Inc. implemented a really nice user interface for signing up (screenshot) that lets you pick your existing hCard-supporting profile on sites like Cork’d, Last FM, Flickr, Technorati, Twitter, Yedda etc. to fill out such basics as your name, your user icon, and URL.

Dopplr friends import screen First XFN+hCard social network import implemented! Mere hours ago, maybe a day ago, Dopplr.com, a currently invite-only travelplan sharing site, implemented the ability to import your contacts from any other site that publishes your contact list with hCard for the people and XFN for your relationship(s) to them, instead of having to manually find and re-add everyone to yet another site. Here is a screenshot of the results.

Examples:
keroro's hCard
http://flickr.com/people/drewm/
http://upcoming.yahoo.com/event/337052/

absolute position的水平&垂直置中

keroro's hCard
在一已知 height & width 的 element,這個技巧蠻不錯的,原理是先設定 top: 50%; left: 50%;,設定 element 的寬與高 height: 18em, width: 30em,再利用 negative margin 把 element shift 寬/高的一半 margin-left: -15em; margin-top: -9em

vcard {
border:1px solid #666666;
height:18em;
left:50%;
margin-left:-15em;
margin-top:-9em;
position:absolute;
top:50%;
width:30em;
}

12/05/2007

YUI 2.4

YUI CSS Selector
Yahoo! UI Library: Selector Utility
cheatsheet

" " Descendant Combinator: “A B”represents an element B that has A as an ancestor.
> Child Combinator: “A > B” represents anelement B whose parent node is A.
+ Direct Adjacent Combinator: “A + B”represents an element B immediately following a sibling element A.
~ Indirect Adjacent Combinator: “A ~ B”represents an element B following (not necessarily immediately following) a sibling element A.


JSON utility - 把 eval() 丟掉吧
// Potentially UNSAFE
var data = eval('(' + shouldBeJsonData + ')');

// Safe
var data = YAHOO.lang.JSON.parse(shouldBeJsonData);

JSON to JavaScript Data
var jsonString = '{"productId":1234,"price":24.5,"inStock":true,"bananas":null}';

// Parsing JSON strings can throw a SyntaxError exception, so we wrap the call
// in a try catch block
try {
var prod = YAHOO.lang.JSON.parse(jsonString);
}
catch (e) {
alert("Invalid product data");
}

// We can now interact with the data
if (prod.price < 25) {
prod.price += 10; // Price increase!
}

JavaScript to JSON
var myData = {
puppies : [
{ name: "Ashley", age: 12 },
{ name: "Abby", age:9 }
]
};

var jsonStr = YAHOO.lang.JSON.stringify(myData);

// jsonStr now contains the string (without the leading comment slashes)
// {"puppies":[{"name":"Ashley","age":12},{"name":"Abby","age":9}]}

// Create a cyclical reference
myData["puppies"][0]["NEWKEY"] = myData;

jsonStr = YAHOO.lang.JSON.stringify(myData);
// jsonStr now contains the string (without the leading comment slashes)
// {"puppies":[{"name":"Ashley","age":12,"NEWKEY":null},{"name":"Abby","age":9}]}

12/04/2007

always show/hide scrollbar in IE/Firefox

Men are greedy. IE always 有 vertical scrollbar 不管 document 的 size 是否超過了 canvas,所以我們想要 hide unnecessary vertical scrollbar

html{overflow:auto}

Always Show Vertical Scrollbar in Firefox [firefox] [css] [web]
html {overflow: scroll;} works but it also gives you a horizontal scroll bar.
html {overflow-y: scroll;} will give you just a vertical scroll bar, if that's what you are going for.

'overflow-x' and 'overflow-y' in Mozilla! - Anne’s Weblog
html {overflow: scroll;} works but it also gives you a horizontal scroll bar.
:root{overflow-y: scroll;}

layerX / layerY / offsetX / offsetY

Two Functions for Retreiving the Position of the Mouse Relative to the Current Element
MSDN Definition

event.offsetX: Sets or retrieves the x-coordinate of the mouse pointer's position relative to the object firing the event.

MDC Definition
event.layerX: Returns the horizontal coordinate of the event relative to the current layer.

// Get the X position of the mouse relative to the element target
// used in event object 'e'
function getElementX( e ) {
// Find the appropriate element offset
return ( e && e.layerX ) || window.event.offsetX;
}
// Get the Y position of the mouse relative to the element target
// used in event object 'e'
function getElementY( e ) {
// Find the appropriate element offset
return ( e && e.layerY ) || window.event.offsetY;
}

screen.width / screen.height / innerWidth / innerHeight / clientWidth / clientHeight / scrollTop / scrollLeft / scrollHeight / scrollWidth

要取得螢幕的resolution有簡單的cross-browser的作法:
MDC Definition

window.screen.height: Returns the height of the screen in pixels.

MSDN Definition
Retrieves the vertical resolution of the screen.

scrollHeight/scrollWidth
MDC Definition
DOM:element.scrollHeight: DHTML property that gets the height of the scroll view of an element; it includes the element padding but not its margin.

MSDN Definition
Retrieves the scrolling height of the object.

YUI:
   var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;


YUI's getDocumentHeight / getDocumentWidth
/**
* Returns the height of the document.
* @method getDocumentHeight
* @return {Int} The height of the actual document (which includes the body and its margin).
*/
getDocumentHeight: function() {
var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;

var h = Math.max(scrollHeight, Y.Dom.getViewportHeight());
return h;
},

/**
* Returns the width of the document.
* @method getDocumentWidth
* @return {Int} The width of the actual document (which includes the body and its margin).
*/
getDocumentWidth: function() {
var scrollWidth = (document.compatMode != 'CSS1Compat') ? document.body.scrollWidth : document.documentElement.scrollWidth;
var w = Math.max(scrollWidth, Y.Dom.getViewportWidth());
return w;
},

YUI's getViewportHeight / getViewportWidth
/**
* Returns the current height of the viewport.
* @method getViewportHeight
* @return {Int} The height of the viewable area of the page (excludes scrollbars).
*/
getViewportHeight: function() {
var height = self.innerHeight; // Safari, Opera
var mode = document.compatMode;

if ( (mode || isIE) && !isOpera ) { // IE, Gecko
height = (mode == 'CSS1Compat') ?
document.documentElement.clientHeight : // Standards
document.body.clientHeight; // Quirks
}

return height;
},

/**
* Returns the current width of the viewport.
* @method getViewportWidth
* @return {Int} The width of the viewable area of the page (excludes scrollbars).
*/

getViewportWidth: function() {
var width = self.innerWidth; // Safari
var mode = document.compatMode;

if (mode || isIE) { // IE, Gecko, Opera
width = (mode == 'CSS1Compat') ?
document.documentElement.clientWidth : // Standards
document.body.clientWidth; // Quirks
}
return width;
},

viewport code from PPK
var x,y;
if (self.innerHeight) // all except Explorer
{
x = self.innerWidth;
y = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
// Explorer 6 Strict Mode
{
x = document.documentElement.clientWidth;
y = document.documentElement.clientHeight;
}
else if (document.body) // other Explorers
{
x = document.body.clientWidth;
y = document.body.clientHeight;
}


How much the page has scrolled.
var x,y;
if (self.pageYOffset) // all except Explorer
{
x = self.pageXOffset;
y = self.pageYOffset;
}
else if (document.documentElement && document.documentElement.scrollTop)
// Explorer 6 Strict
{
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
}
else if (document.body) // all other Explorers
{
x = document.body.scrollLeft;
y = document.body.scrollTop;
}

Reference:
JavaScript - Window manipulation
Viewport introduction
Viewport - Properties

clientX / clientY / pageX / pageY

對一個 event 而言,我們常會用到的是 event 的(1)距離 document 左邊距離多少 / (2)距離 document 上面距離多少。
W3C Definition

clientX of type long, readonly
The horizontal coordinate at which the event occurred relative to the DOM implementation's client area.
clientY of type long, readonly
The vertical coordinate at which the event occurred relative to the DOM implementation's client area.

MDC Definition
event.clientX: Returns the horizontal coordinate within the application's client area at which the event occurred (as opposed to the coordinates within the page).
event.pageX: Returns the horizontal coordinate of the event relative to whole document.

DOM標準中,未明確定義 clientX 與 clientY 是相對於 canvas 還是 document,Firefox的作法是以 canvas 為準,並且另外定義以 document為準的 pageX 與 pageY。IE的 implement 是以 canvas 為準,所以需要加上捲軸的高度。其他的瀏覽器(Opera Konqueror iCab)


所以
by document: Mozilla Firefox (pageX/pageY),Opera, Konqueror, iCab
by canvas: Mozilla Firefox (clientX/clientY),IE


var ex, ey;
if(e.pageX && e.pageY){ // Mozilla Firefox
ex = e.pageX;
ey = e.pageY;
}
else if(e.clientx && e.clientY){
ex = e.clientx;
ey = e.clientY;
if(isIE){ // add scrollLeft, scrollTop to it.
ex += document.body.scrollLeft;
ey += document.body.scrollTop;
}
}

ref: PPK - JavaScript - Find position

offsetHeight / offsetWidth / offsetTop / offsetLeft

對一個 element 而言,我們常會用到的是 element 的(1)寬 / (2)高 / 與 (3)document 左邊距離多少 / (4)與 document 上面距離多少。
(1) elemenet 的寬就是 element.offsetWidth
(2) elemenet 的高就是 element.offsetHeight
(3) offsetTop 是 element 與 offsetParent 的距離。所以(3)的算法就是一直累加 offsetParent 的 offsetLeft,code 如下:

function findPosX(obj){
var curLeft = 0;
do{
curLeft += obj.offsetLeft;
} while(obj = obj.offsetParent);
}
return curLeft;

(4) 同理 offsetLeft 的算法為
function findPosX(obj){
var curTop = 0;
do{
curTop += obj.offsetTop;
} while(obj = obj.offsetParent);
}
return curTop;

12/03/2007

John Resig - Easy PDF Sharing

John Resig - Easy PDF Sharing - 用 Image Magic 把 pdf 轉成 png 在輸出在頁面上 - cool。下面中的 comment 有 slideshare 的人提到為什麼他們選擇用 swf 而不是 jpg/png 是因為 scaling 的問題。

SWFs scale very neatly and we can have players of different sizes from embeds to full screen.

source code

Better ways to writing JavaScript

Better ways to writing JavaScript

function get(el) {
return document.getElementById(el);
}
//usage:
$('foo', 'bar', 'baz');

var addEvent = function() {
if (window.addEventListener) {
return function(el, type, fn) {
el.addEventListener(type, fn, false);
};
} else if (window.attachEvent) {
return function(el, type, fn) {
var f = function() {
fn.call(el, window.event);
};
el.attachEvent('on' + type, f);
};
}
}();
//usage:
addEvent(get('example'), 'click', function(e) {
alert('hello world');
});

var asyncRequest = function() {
function handleReadyState(o, callback) {
if (o && o.readyState == 4 && o.status == 200) {
if (callback) {
callback(o);
}
}
}
var getXHR = function() {
var http;
try {
http = new XMLHttpRequest;
getXHR = function() {
return new XMLHttpRequest;
};
}
catch(e) {
var msxml = [
‘MSXML2.XMLHTTP.3.0′,
‘MSXML2.XMLHTTP’,
‘Microsoft.XMLHTTP’
];
for (var i=0, len = msxml.length; i < len; ++i) {
try {
http = new ActiveXObject(msxml[i]);
getXHR = function() {
return new ActiveXObject(msxml[i]);
};
break;
}
catch(e) {}
}
}
return http;
};
return function(method, uri, callback, postData) {
var http = getXHR();
http.open(method, uri, true);
handleReadyState(http, callback);
http.send(postData || null);
return http;
};
}();
usage:
asyncRequest('GET', 'test.php?foo=bar', callback);
function callback(o) {
alert(o.responseText);
}

editCSS for Internet Explorer

crisp's blog » Blog Archive » editCSS for Internet Explorer - concept - 底下的comment有提到accessibility toolbar,在CSS->Test Styles->選一個element,點edit style rule。
sourcecode

Now I was finally in business and so I present to you a simple concept of an editCSS feature in Internet Explorer (this link will only work in IE ofcourse…)

Not to mention that this is only a concept and has a lot of limitations: it doesn't work for stylesheets on another domain (since it uses XMLHttpRequest and thus is origin-bound), it doesn't really take into account media-types, the rules for alternate stylesheets are not really respected, it doesn't allow you to modify inline style-elements, it doesn't take into account @import or @media rules, it's a popup instead of a sidebar etcetera etcetera.

YUI Dimension api

getViewportHeight
Int getViewportHeight ( )
Returns the current height of the viewport.

Returns: Int
The height of the viewable area of the page (excludes scrollbars).



getRegion
Region | Array getRegion ( el )
Returns the region position of the given element. The element must be part of the DOM tree to have a region (display:none or elements not appended return false).

Parameters:
el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.

Returns: Region | Array
A Region or array of Region instances containing "top, left, bottom, right" member data.


getDocumentWidth
Int getDocumentWidth ( )
Returns the width of the document.

Returns: Int
The width of the actual document (which includes the body and its margin).


getDocumentScrollTop
Int getDocumentScrollTop ( document )
Returns the top scroll value of the document

Parameters:
document (optional) The document to get the scroll value of

Returns: Int
The amount that the document is scrolled to the top


getXY
Array getXY ( el )
Gets the current position of an element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).

Parameters:
el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements

Returns: Array
The XY position of the element(s)

gmail fragment identifiers

http://mail.google.com/mail/?shva=1#inbox/1169c4949d7598d6

#後面那一串就是 fragment identifiers, 可以讓 JavaScript keep 目前的 state, 像是目前使用者正在看的 tab, 不會因為使用者 refresh 之後就回到最初的狀態, 比較特別的是#後面還有inbox/, 看來可以好好利用一下。

Menu Editor :: Firefox Add-ons

Menu Editor :: Firefox Add-ons - 可有效去除context menu過長的毛病,尤其在過多的add-on都想佔據contenxt menu的情況下。

Rearrange or remove menuitems from the main context menu (right-click menu) and main menubar (File Edit View etc.)

IE fix

作者 coolfiretw (冷炎TM) 看板 Fuck
標題 Re: IE好像爛掉了
時間 Thu Nov 29 00:13:43 2007

※ 引述《whchu (風吹隨便倒...)》之銘言:
: IE用到一半,沒事就會出現ntdll.dll錯誤,然後就死掉。
: 拿winxp光碟片用修復裝一次也修不好。
: 幹!
試試看萬能解決法吧.....

重新註冊全部的DLL:
for %1 in (%windir%\system32\*.dll) do regsvr32.exe /s %1

反正一堆鳥問題,大部份都能解決.

12/02/2007

javascript pseudo-protocol HREF is harmful

http://kitty.2y.idv.tw/~chfang/test-revised.htm
odd problem about innerHTML & img under IE - comp.lang.javascript | Google 網上論壇

Executing a javascript pseudo-protocol HREF in IE browsers (at least up
to 6) convinces the browser that it about to navigate away from the
current page (as would be the normal consequence of following the HREF
of a link) and puts the browser into a 'waiting' stat in witch various
facilities stop working (or working in the previously expected way). One
of the more often observed symptoms is the browser failing to
load/display new images. This is usually reported as the unexpected
stopping of image swapping with rollovers, but any failure in an image
related operation after the execution of a javascript pseudo-protocol
HREF might be attributed to this.

Richard.

crisp's blog » Blog Archive » The useless javascript: pseudo-protocol

It comes down to this: when you use this in for instance an href-attribute you are most probably misusing an anchor-element for something that is not related to navigation. "You should not use a link for anything else but a link" - it's the basis of the web: links are for navigation and not for in-page behavior*. Got that?

Note the 'return false': this prevents a JS-capable client to actually start navigating to 'alternative.html'. That brings us to another problem with the javascript: pseudo-protocol, namely the fact that IE (at least up to version 6) enters a different 'state' when the href of a link is being followed no matter if it contains an actual link or a javascript function. This is most noticable when you have animated gifs on your page: when such a link is clicked they stop animating, and there are probably more problems that can arise from this 'state'-change in Internet Explorer. Wrapping your function-call in the void() operator doesn't change that either.

Re: A tag: href vs. onClick
update: 可以用< a id="next" href="#">
YUE.on('next', 'click', function(e){
doSomething();
YUE.stopEvent(e);
return fasle
})

11/30/2007

Dean Edwards: The window.onload Problem - Solved!

Dean Edwards: The window.onload Problem - Solved! - 本來探討 window.onload,通常window.onload = init; init會等到頁面所有的compoent load完之後開始動作(包含所有的img & binary content),這樣有時候不是很理想,譬如一個很多圖的頁面,必須等到圖全部load完才會開始執行init,FF可以利用"DOMContentLoaded" IE可以利用defer來達成。
1. conditional comment

<!--[if IE]> ... <![endif]-->

conditional compilation
/*@cc_on @*/
/*@if (@_win32)
document.write("<script defer src=ie_onload.js><\/script>");
/*@end @*/

2. Mozilla Firefox
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}

Internet explorer
<script defer src="ie_onload.js" type="text/javascript"></script>

Dean Edwards: window.onload (again)

// for Internet Explorer (using conditional comments)
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/


http://livepipe.net/scripts/code_highlighter.js

function asap(fn) {
asap.done ? setTimeout(fn, 0) : asap.waiting.push(fn);
}
asap.waiting = [];
asap.done = 0;
asap.ready = function() {
// (note: deliberately avoids using 'this')
if (!asap.done++) {
asap.timer && clearInterval(asap.timer);
var funcs = asap.waiting;
for (var i = 0, l = funcs.length; i < l; i++) {
setTimeout(funcs[i], 0);
}
}
}
// IE
/*@cc_on@if(@_win32)document.write('')@end@*/
// Moz/Op
document.addEventListener && document.addEventListener('DOMContentLoaded', asap.ready, false);
// Safari
asap.timer = navigator.userAgent.match(/WebKit|KHTML/i) && setInterval(function() { document.readyState.match(/loaded|complete/i) && asap.ready() }, 10);
// Fallback
window.onload = asap.ready;

之後要呼叫的function都經由 asap('Syntax.init()'); 這樣呼叫即可

Indenting CSS

Indenting CSS - 非常有創意的寫法,第一種寫法是依照 selector 的 weight 排序,實際上蠻難( to me at least )即時判斷selector的權重,第二種寫法的可行性蠻高的,是依照 HTML 的 structure 下去寫的,下次來試看看。


table.data_table {
}
table.data_table tr {
}
table.data_table tr td {
}
table.data_table tbody {
}
table.data_table tbody td {
}



1. div#box {
2. background-color: #FFF;
3. border: 1px solid #2E5E81;
4. margin: 50px auto 0 auto;
5. width: 790px;
6. }
7.
8. div#top, div#bottom {
9. background-color: #ADDCFF;
10. height: 25px;
11. line-height: 25px;
12. }
13.
14. div#main {
15. background: transparent url(../images/background.png) 10px 10px no-repeat;
16. height: 500px;
17. }
18.
19. div#content {
20. background-image: url(../images/png/50.png);
21. height: 500px;
22. margin: 25px 25px 25px 395px;
23. padding: 10px 10px 10px 10px;
24. }


<body>
<div id="box">
<div id="top">
<div id="main">
<div id="content">
</div>
<div id="bottom"></div>
</div>
</body>

11/29/2007

LukeW: Primary & Secondary Actions in Web Forms

LukeW: Primary & Secondary Actions in Web Forms - 這篇文章針對 primary action / secondary action所需要的視覺上的 distinction 上做探討,primary action指的是像 sumbit/發佈文章 之類大部分人所選擇的選項,secondary action 指的是像 cancle/立即儲存 之類比較次要的選項,在他的測試中,獲得最佳效果的是B,其次是C,這蠻有趣的,這中間有取捨,B的效率會較高,C的誤按的機率會比較小,最差效果的是把兩個 button 放離有一段距離的 E。

img.onreadystatechange

今天遇到一個很奇怪的問題,來 memo 一下,問題是這樣子的,分頁的圖出不來,IE only,後來發現是因為如果圖還沒 load 完就 append 到 Dom tree 上,IE似乎會停止 load 那張圖,解法就是設一個onreadystatechange的event handler,並且檢查目前的state是否為complete,再 append 到Dom tree上面。以上都是IE only,FF直接 append 到 Dom tree不會有問題

centerWrap = document.createElement('div');
img = document.createElement('img');
img.src = item[i].getAttribute('rel');

if(document.all){
centerWrap.id = item[i].getAttribute('rel');
img.onreadystatechange = function(e){
if(this.readyState == 'complete'){
$(this.src).appendChild(this);
}
}
}
else{
centerWrap.appendChild(img);
}

update: 上面這個作法會有問題:第二次 visit 分頁的圖會出不來,原因是因為第一次 visit 的時候IE會把圖 cache 起來,第二次visit的時候會直接從cache讀出來,所以不會發生onreadystatechange的 event,所以圖的 node 也不會 append 到 Dom tree上。解法是把不確定是否有cache住的都用 time stamp force retrival。

Tsung's Blog | 寫 JavaScript 需要的 VIM Syntax 和 Plugin 檔

Tsung's Blog | 寫 JavaScript 需要的 VIM Syntax 和 Plugin 檔

11/27/2007

Ajaxian » URI vs. URL: What’s the difference?

Ajaxian » URI vs. URL: What’s the difference?

URI

A URI identifies a resource either by location or name. More often than not, most of us use URIs that defines a location to a resource. However, a URI does not have to specify the location of a specific representation. Citing and example of a W3C URI for their home image, they use the following URI: http://www.w3.org/Icons/w3c_home. Note the absence of a file extension. The URI for the w3c_home image is still universally unique, but it does not specify the specific representation of the image (either a GIF, PNG, or JPG). The selection of the representation can be determined by the web server through HTTP content negotiation. The Apache HTTPD server has had excellent support for content negotiation for many years. Oddly, few sites take advantage of HTTP content negotiation. The W3C is one web application that makes heavy use of URIs and content negotiation.

URL

A URL is a URI but a URI is not a URL. A URL is a specialization of URI that defines the network location of a specific representation for a given resource. Taking the same W3C example, there are actually 2 representations available for the w3c_home resource:

* http://www.w3.org/Icons/w3c_home.gif
* http://www.w3.org/Icons/w3c_home.png

These URIs also define the file extension that indicates what content type is available at the URL. Through content negotiation, the web server will forward the user agent to the proper type, depending on the client’s capabilities, when the URI http://www.w3.org/Icons/w3c_home is accessed.

More often than not, URI is the correct term to use when referring to the location of resources on the WWW.

Content negotiation - Wikipedia, the free encyclopedia
Content negotiation is a mechanism defined in the HTTP specification that makes it possible to serve different versions of a document (or more generally, a resource) at the same URI, so that user agents can choose which version fit their capabilities the best. One of the most classical uses of this mechanism is to serve an image as both GIF and PNG, so that a browser that doesn't understand PNG can still display the GIF version. To summarize how this works, it's enough to say that user agents are supposed to send an HTTP header (Accept) with the various MIME types they understand and with indications of how well they understand it. Then, the server replies with the version of the resource that fits the user agents' needs.

11/23/2007

beautiful web sites

Particletree
particletree.com
particletree.com.blog
Stylegala - Web Design Publication
www.stylegala.com
456 Berea Street: Articles and news on web standards, accessibility, and usability
www.456bereastreet.com
Rosenfeld Media - Web Form Design Best Practices
www.rosenfeldmedia.combookswebforms
www.rosenfeldmedia.com
http://css-tricks.com/links-of-interest-9/
css-tricks.comlinks-of-interest-9
blog design
Julien Lecomte’s Blog » Introducing CrossFrame, a Safe Communication Mechanism Across Documents and Across Domains - 800px centered column & shadow image
www.julienlecomte.netblog20071131

browser cache

在開發的時候,常常會發生的事,CSS/JS 被 browser cache 住,沒更新,以為寫的 code 沒有起作用,查半天才發現是cache問題,所以,需要瞭解1. 如何快速的刪cache:IE要click六次, 2. 在密集開發的時候,乾脆disable cache。


Cache path
  • Internet Explorer: C:\Documents and Settings\user\Local Settings\Temporary Internet Files
  • Firefox about:config -> browser.cache.disk.parent_directory
  • Firefox about:cache可以列出Memory cache device & Disk cache device的每個cache住檔案的path以及資訊。

Clear cache
  • Internet Explorer: 工具->網際網路選項->刪除檔案->勾選"刪除所有離線檔案"->確
  • Firefox: ctrl+shift+del -> 勾選"快取" -> 確定
  • Firefox Add-ons Cache Status

Disable cache
  • 工具->網際網路選項->設定->檢查儲存的畫面是否有較新的版本->每次查閱畫面時
  • Firefox: about:config -> browser.cache.check_doc_frequency -> Highlight and double click. Change the 3 (default) to 1 (which signifies "Check every time I view the page") in the dialogue box. Click OK.
  • Firefox Add-ons Web developer disable-> cache

forece reterival
  • add time stamp to file ex: <script src="foo.js?235235235235">
    time stamp can be generated by new Date.valueOf();
References:
How to Disable Your Browser Cache — Psychology IT

11/21/2007

Textarea Maxlength

PPK - Textarea Maxlength

The purpose of my script is not to enforce the maximum length, though it can easily be changed to do that. However, I decided to restrict my script to giving a polite reminder when the user exceeds the maximum amount of characters. Actually enforcing this maximum length is left to the trim_to attribute of Movable Type, which, being a server side functionality, is impossible for users to turn off.
  1. textarea是沒有maxlen屬性的, 不過我們可以用javascript來implement, 不過目前市面上的作法通常是取substring(0, textarea.getAttribute('maxlen'))之類的, 這樣做法有一個缺點: 在IE會一直focus到textarea內文最後的地方。
  2. 再者, javascript很容易可以被disable掉, 無法提供一個安全的限制, 只能拿來當作提醒的用途, 在這篇文章中, ppk建議的方法是: 超過maxlen的話, 提示他就好了, 紅色的字之類的
  3. 注意文中counterClone.relatedElement = x[i]; 取得reference之後就bind在relatedElement裡面, 方便之後的access, 不需要每次都去取reference

11/17/2007

time stamp in javascript

new Date().valueOf();

comp.lang.javascript FAQ - 9.88 - 2007-10-12
Date.valueOf( ): convert a Date to millisecond representation
Object.valueOf( ): the primitive value of the specified object
To reload a page, use location.reload(). However, this depends upon the cache headers that your server sends. To change this, you need to alter the server configuration. A quick fix on the client is to change the page URI so that it contains a unique element, such as the current time. For example: location.replace(location.href+'?d='+new Date().valueOf()) If the location.href already contains a Query String, use: location.replace(location.href+'&d='+new Date().valueOf())

11/15/2007

圖片的水平置中以及垂直置中

Centering (horizontally and vertically) an image in a box
Demo
update: 上面的例子在ie7不會work
Demo - work in ie6, ie7, firefox
<div id="wrap">
<img src="http://developer.yahoo.com/yui/docs/assets/logo.gif">
</div>
圖片的水平置中的標準作法是#wrap{text-align:center},text-align:center是用來定位在block elemenet裡的inline element,圖片也是個inline element,FF & IE都沒問題。




比較麻煩的是圖片的垂直置中,FF以及一些標準的browser可以通過下面的方法置中


11/09/2007

note about iframe

1. iframe id="iframe" , 用 document.getElementById('iframe') 在 IE 下會抓不到,換一個 id 即可。待確認

2. 完全清除 iframe 的 border 單靠 CSS 是不夠的,要設定 iframe frameborder="0",設定後即可用 CSS control border style, ex: iframe{border: 1px solid #36c}

PPK - Javascript - Iframes


  1. The most important rule is to give any iframe you create a name attribute, even if you also use an id.
  2. alert(frames['inner'].document.body.innerHTML)

http://chunghe.googlepages.com/outter.htm

10/31/2007

keyCode and keyEvent: onkeydown onkeypress onkeyup

要利用鍵盤來進行操作,首先要先在document bind一個key event,key event(至少)有三個,keydown, keypress, keyup,測試一下這些key event能否抓到正確的key code,測試的script如下

<body>
empty document
</body>
<script>
document.onkeyup = function(e){
if(!e) e = window.event;
alert(e.keyCode)'
}

keyup: IE OK, FF: OK
keydown: IE OK, FF: OK
keypress; IE: 英文數字OK, 方向鍵not OK FF: not OK

另外keydown可以在使用者一直按著某個鍵時,持續的產生event,如果想做一個一直按著某個鍵,重複一些動作,keydown會是很好的人選。
ex: http://chunghe.googlepages.com/keycode-and-keyevent-onkeydown.htm
在這個例子中,持續按著就會一直產生key event,不需要setInterval之類的咚咚

10/29/2007

Abbreviation vs. Acronym

Oxford English Dictionary


  • Abbreviation: A shortened form of a word or phrase.

  • Acronym: A word formed from the initial letters of other words (e.g., laser, which is an acronym of Light Amplification by Stimulated Emissio of Radiation).

  • Initialism: An abbreviation consisting of initial letters pronounced separately(e.g., BBC).

all acronyms and initialisms are abbreviations, but not all abbreviations are acronyms or initialisms.

10/28/2007

div的高度

遇到一個問題,一個空的DIV,高度會是多少?

<div style="width:150px; background-color:red;"></div>
IE: 高度19px
FF: 0

如果強制設定高度為0px,高度會是多少?這個就有趣了
<div style="width:150px; height:0px; background-color"></div>
IE: 高度19px
FF:0

可能是字型的原因,把字型設為0px看看
<div style="width:150px; height:0px; font-size: 0px; background-color"></div>
IE: 高度2px
FF:0

看起來是有點效果,但是要如何才能讓他高度為0? IE div height problem
1) Put a comment inside the div:  <div style="height: 10px;"><!-- --></div>
2) Put a &nbsp; inside the div and add this to its style: font-size:1px;
line-height:0.

第一招蠻神奇的,只要不設定height,就不會顯示出該div,both work in IE && FF
在有內文的情形下,就用第二招吧
<div style=" width: 150px;  font-size:1px; line-height:0; background-color: red ">foo</div>

10/20/2007

如何使用z-index蓋住flash

Tsung's Blog | CSS: 讓圖片蓋在 Flash Player 上面(使用 z-index) - 最近遇到一個一模一樣的問題, 一個z-index比較大的 element 蓋不住 flash, 解法是設定為 wmode="opaque"


  • wmode = "window" , default, flash player在最上層
  • wmode = "opaque" , flash player 介於 element 與 element的背景中間
  • wmode = "transparent", flash player 位於 element 的背景下方
針對 <object>/<embed> 的設法:
* 於 <object> 內加 <param name="wmode" value="transparent">, ex: <object>.... <param name="wmode" value="transparent"> ...</object>
* 於 <embed> 內加 wmode="transparent" 參數, ex: <embed wmode="transparent" ....>

針對 AC_RunActiveContent.js 的設法:

* 於 AC_FL_RunContent() 多加 'wmode', 'transparent' 的參數, ex: AC_FL_RunContent(.... 'wmode', 'transparent' ...);
* <noscript> 內, 應該最好也要加如上述 <object>/<embed> 的參數.

javascript idiom: getComputedStyle + currentStyle

The first argument to this method is the element whose computed style is desired. The second argument is any CSS pseudoelement, such as ":before" or ":after" whose style is desired. You probably won't be interested in a pseudoelement, but in the Mozilla and Firefox implementation of this method, the second argument is required and may not be omitted.

var p = document.getElementsByTagName("p")[0]; // Get first paragraph of doc
var typeface = ""; // We want its typeface
if (p.currentStyle) // Try simple IE API first
typeface = p.currentStyle.fontFamily;
else if (window.getComputedStyle) // Otherwise use W3C API
typeface = window.getComputedStyle(p, null).fontFamily;

Computed styles are quirky, and querying them does not always provide the information you want. Consider the typeface example just shown. The CSS font-family attribute accepts a comma-separated list of desired font families for cross-platform portability. When you query the fontFamily attribute of a computed style, you're simply getting the value of the most specific font-family style that applies to the element. This may return a value such as "arial,helvetica,sans-serif", which does not tell you which typeface is actually in use. Similarly, if an element is not absolutely positioned, attempting to query its position and size through the top and left properties of its computed style often returns the value "auto". This is a perfectly legal CSS value, but it is probably not what you were looking for.

update:
  1. YUI的 YAHOO.util.Dom.getStyle(el, 'fontFamily') 的傳回值仍然是整組的css property.( ex: arial, verdana, sans-serif);
  2. 以下的例子是使用抓取 pseudoelement 'hover' 的方法
    console.log( window.getComputedStyle($('link'), 'hover').color );
    <a id="link" href="#">l;www.foo.bar</a>
    傳回值: rgb(0, 0, 238),明顯是錯誤的答案。(rgb(0, 0, 238)是FF預設的a:link color)
    Re: How is the hover pseudo-class translated into the DOM? from Bjoern Hoehrmann on 2007-03-26 (www-dom@w3.org from January to March 2007)
    Ok, here's the tricky part, according to this article, the only way to get the hover color is to fire getComputedColor() while hovering it. You can't set the second parameter to hover 'cause it's not a psudo-element, it's only a matching condition. Here's the example
    window.onload = function(){
    $('link').onmouseover = function(){
    console.log( window.getComputedStyle($('link'), null).color );
    }
    }
    the return value will be rgb(255, 0, 0) which is correct.

10/17/2007

YUI code snippets

Photo Batching | ThinkVitamin.com
Skinning JS solutions - CSS JavaScript friction and fusion - 這種寫法的好處是
1. 使用者reload不會總是回到第一個tab: 技巧是toc裡面的<a href>帶有#號,自然location.href裡面就有#號,然後在某個tab做reload的話,可以判斷使用者原本在的tab,不會每次都回到第一個tab。
2. click event是 bind 在 toc 裡面,再由 YAHOO.util.event.getTarget(e)去抓取實際點取到的 tab,不需要每個 tab 都 bind 一個 click listener
3. 最後 return pub,只有pub是pub.init是pulic method,其餘的getBookmark, show都是private method


<ul id="toc">
<li><a href="#spec1">Spec 1</a></li>
<li><a href="#spec2">Spec 2</a></li>
<li><a href="#spec3">Spec 3</a></li>
<li><a href="#spec4">Spec 4</a></li>
<li><a href="#spec5">Spec 5</a></li>
</ul>

YAHOO.example.tocnav = function(){
var pub = {};
function show(e){
var t = YAHOO.util.Event.getTarget(e);
if(t.nodeName.toLowerCase()==='a'){
if(pub.current){
YAHOO.util.Dom.removeClass(pub.current,'show');
}
var target = YAHOO.util.Dom.get(t.href.split('#')[1]);
if(target){
pub.current = target.parentNode;
YAHOO.util.Dom.addClass(pub.current,'show');
}
}
};
function getBookmark(){
var bookmark = window.location.hash.replace('#','');
var t = YAHOO.util.Dom.get(bookmark);
return t ? t.parentNode : false;
};
pub.init = function(){
pub.current = getBookmark();
YAHOO.util.Dom.addClass(this,'js');
YAHOO.util.Dom.addClass(pub.current,'show');
YAHOO.util.Event.addListener('toc','click',show);
};
return pub;
}();
YAHOO.util.Event.onAvailable('faq',YAHOO.example.tocnav.init);

Reading out element dimensions with YUI Region
ver Y = YAHOO.util;
var $D = Y.Dom;
var $E = Y.Event;
var $ = $D.get;


YAHOO.util.Dom.setStyle(['test', 'test2'], 'opacity', 0.5);
var opacity = YAHOO.util.Dom.getStyle('test2', 'opacity');


/* return 放 public method, 其他private放在return之前 */
YAHOO.MyProperty = function () {
var privateVariable;
function privateFunction(x) {
...privateVariable...
}
return {
firstMethod: function (a, b) {
...privateVariable...
},
secondMethod: function (c) {
...privateFunction()...
}
};
}();

1. onAvailable 裡面可以用 this,這邊指的是 'yui-main',用在getElementsByClassName的第三個參數可以限定只在 'yui-main' 裡面找
2. getRegion 可以取得 block 的上下邊的 y 軸座標以及左右邊的 x 軸座標, ex:
var region = YAHOO.util.Dom.getRegion ( YAHOO.util.Dom.get('test') );
回傳 Region {top: 32, right: 825, bottom: 1334, left: 173}
可用region.top / region.bottom 取得 border-top / border-bottom 的 y 軸座標
region.left / region.right 取得 border-left / border-right 的 x 軸座標

另外也可以用getXY取得左上角的座標, ex:
var region = YAHOO.util.Dom.getXY ( YAHOO.util.Dom.get('test') );

回傳 [173, 32] 分別對應到上一個 region.left region.top, 也就是該element的
左上角的[x軸, y軸] 座標
3. height = reg.bottom - reg.top; 可以決定 div 的高度。

YAHOO.util.Event.onAvailable('yui-main',function(){
var reg = YAHOO.util.Dom.getRegion(this.getElementsByTagName('div')[0]);
var height = reg.bottom - reg.top;
var grids = YAHOO.util.Dom.getElementsByClassName('yui-u','div',this);
for(var i=0;grids[i];i++){
YAHOO.util.Dom.setStyle(grids[i],'height',height+'px');
};
});

YAHOO.util.Dom.getDocumentHeight(); // 取得整個document的高
YAHOO.util.Dom.getDocumentWidth();
YAHOO.util.Dom.getViewportHeight()); // 取得可視範圍的高
YAHOO.util.Dom.getViewportWidth());

1. 示範namespace的用法, 預設的namespace定義在YAHOO global object, 只有YAHOO.util YAHOO.example, YAHOO.widget
2. $E.on的是$E.addListener的alias, 第一個參數可以傳一個id的array, 函數中的this同樣是指到 apply 的 element, 這邊是 $('test1') or $('test2')
3. 通過 setStyle(el, 'opacity', '0.7') 可以快速的設定opacity, 最後一個參數是 follow standard 0-1之間的opacity
4. 利用return 來區別private & public, 整各YAHOO.foo.bar.example是一個函式, 外界無法更動裡面的職, data hiding.

YAHOO.namespace('foo.bar');
var y = YAHOO.util;
var $E = y.Event;
var $D = y.Dom;
var $ = $D.get;
var $$ = $D.getElementsBy;

YAHOO.foo.bar.example = function(){
return {
init: function(){
$E.on(['test1', 'test2'], 'click', function(){
$D.setStyle(this, 'backgroundColor','red');
$D.setStyle(this, 'opacity', '0.7');
})
}
}
}()
$E.onDOMReady(YAHOO.foo.bar.example.init);

10/16/2007

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet - 太常看到這串字了,特別查了一下,沒想到歷史這麼悠久,還有Firefox addon: Dummy Lipsum,有趣。

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

另外還有各種不同的假文產生器:
亂數假文產生器 - Chinese Lorem Ipsum
Lorem ipsum 以外的新選擇 ¶ Lvx ex Cælis

z-index

Relatively Absolute @ The Autistic Cuckoo
1. 在position: absolute下,除了IE以外,皆可以藉由同時指定top left bottom right由瀏覽器算出block的長跟寬。
2. 有關 z-index,我一直以為是直接設定element的z-index,應該是要設定containing block的z-index,文末指出的例子值得好好想一想,改天再來做個實驗。

When positioned elements overlap, we can control the stacking order with the
z-index property. The higher the z-index, the closer
to the user the element ends up. Unfortunately this isn't quite as
straightforward as it sounds, since each containing block establishes its own
context for z-index. So to put one element on top of another
element, with a different containing block, you need to increase the
z-index for the first element's containing block. In
really complex layouts you can find yourself in impossible situations, if you
want to stack three elements where the middle one has a different containing
block than the other two. As far as we know, this cannot be done.


update:
CSS Z-index Property
Note: Z-index only works on elements that have been positioned (eg position:absolute;)!

Always Show Vertical Scrollbar in Firefox [firefox] [css] [web]

Always Show Vertical Scrollbar in Firefox [firefox] [css] [web] - 為什麼要always show vertical scrollbar in Firefox?在IE中,vertical scroll bar 會一直在,不管content的長短,這反而解決了一個問題:在一個置中的欄位中,如果內容太長,Firefox會出現 scrollbar並且佔掉部分的document width,導致置中的欄位移動,畫面不美觀,目前沒有太好的解決辦法,先讓FF的scrollbar一直在吧。

/* always show scrollbar in FF  */
html {
overflow: -moz-scrollbars-vertical;
}
/* hide necessary scrollbar for textarea in IE */

* html textarea{
overflow:auto;
}

update: there's a side effect: horizontal scrollbars will never appear
* -moz-scrollbars-horizontal: Indicates that horizontal scrollbars should always appear and vertical scrollbars should never appear.
* -moz-scrollbars-vertical: Indicates that vertical scrollbars should always appear and horizontal scrollbars should never appear.
* -moz-scrollbars-none: Indicates that no scrollbars should appear but the element should be scrollable from script. (This is the same as hidden, and has been since Mozilla 1.6alpha.)

Forcing Firefox to always show a scroll bar - TOLRA Community Forums
Adding the following to your CSS file causes Firefox to always show the scroll bar:
Code:

html { min-height: 100%; margin-bottom: 1px; }

The normal operation is for Firefox to remove the scroll bar if it's not needed which can lead to the page shifting left and right slightly between long and short pages.

update: this is one perfect solution
Always Show Vertical Scrollbar in Firefox [firefox] [css] [web]
html {overflow: scroll;} works but it also gives you a horizontal scroll bar.
html {overflow-y: scroll;} will give you just a vertical scroll bar, if that's what you are going for.

10/15/2007

IE/win Expanding Box

IE/win Expanding Box - 這篇討論一個IE的bug,對於一個fixed width的DIV container,裡面的content 如果比 container 還要長的話,guess what? IE會把fixed width的 container 稱大來match 裡面的 content,genius!
W3C standard 規定 overflow 的 default 是 visible,就是過長的內容會跑到 container 外面,可能會蓋到外面的內容。
這個 bug 沒有解法,只有workaround,也就是用word-wrap: break-word;把過長的行斷掉,注意這是 IE only 的 property。所以

<!--[if IE]>
<style type="text/css">
body {word-wrap: break-word;}
</style>
<![endif]-->


另一個作法是overflow:hidden,
Another drawback of the "hidden" method is that IE/win demands that the boxes having this overflow fix must have widths applied to them. So for example, consider a nested paragraph in one of those floated columns above. The floats do have widths but the nested paragraph will normally be left widthless. If the overflow: hidden; trick is used on the paragraph, it will fail in IE/Win. But, if it's used on the surrounding float it will then work properly, because the element with the overflow rule also has a width applied to it.

In summary, both word-wrap: break-word and overflow: hidden are possible workarounds that will make Internet Explorer respect our specified dimensions. The method of overflow: hidden works in more situations -- such as oversized images and vertical expansions, but at the cost of possibly clipped content. The word-wrap: break-word; method won't clip content, but is useless on anything but text. Now that you have seen the effects of both, their possible employment will depend on specific situations and preferences.

10/13/2007

只要加一行,讓 IE 五倍速執行 JavaScript ¶ Lvx ex Cælis

只要加一行,讓 IE 五倍速執行 JavaScript ¶ Lvx ex Cælis - 之前不知道在那邊有看到,不明白他的道理,anyway,這一篇解釋的很清楚。

/*@cc_on _d=document;eval('var document=_d')@*/


/*@cc_on
eval((function(props) {
var code = [];
for (var i = 0 l = props.length;i<l;i++){
var prop = props[i];
window['_'+prop]=window[prop];
code.push(prop+'=_'+prop)
}
return 'var '+code.join(',');
})('document self top parent alert setInterval clearInterval setTimeout clearTimeout'.split(' ')));
@*/