Archive Page 2

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);        }    });

Custom Event

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

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");

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.

How to Answer 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

Google Chart API

Understanding and Solving Internet Explorer Leak Patterns

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

Via: Tsung’s Blog | IE 偵測 Memory Leaks 的程式

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;}

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 UNSAFEvar data = eval('(' + shouldBeJsonData + ')');

// Safevar 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 blocktry {    var prod = YAHOO.lang.JSON.parse(jsonString);}catch (e) {    alert("Invalid product data");}

// We can now interact with the dataif (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 referencemyData["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}]}

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.

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, Geckoheight = (mode == 'CSS1Compat') ?document.documentElement.clientHeight : // Standardsdocument.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, Operawidth = (mode == 'CSS1Compat') ?document.documentElement.clientWidth : // Standardsdocument.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;

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/, 看來可以好好利用一下。

« Previous PageNext Page »