Hiển thị các bài đăng có nhãn javascript. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn javascript. Hiển thị tất cả bài đăng

Thứ Hai, 14 tháng 4, 2014

Set location.hash value

if(history.pushState) {
    history.pushState(null, null, "#data");
}
else {
//for ie, not use "#"
    window.location.hash = "data";
}

Thứ Sáu, 20 tháng 12, 2013

Javascript clone object

cloneObj = function(obj){
  if(ko.isWriteableObservable(obj)) return ko.observable(obj()); //this is the trick
  if(obj === null || typeof obj !== 'object') return obj;

  var temp = obj.constructor(); // give temp the original obj's constructor
  for (var key in obj) {
    temp[key] = cloneObj(obj[key]);
  }

  return temp;
};
(http://stackoverflow.com/questions/14055279/javascript-clone-object-with-knockoutjs-observable-properties?rq=1)

Thứ Bảy, 24 tháng 11, 2012

Javascript – Unit Test với QUnit

Unit test là công việc quen thuộc của các lập trình viên để kiểm tra một đơn vị mã nguồn có hoạt động chính xác hay không. Nếu bạn là một javascript coder và đang tìm kiếm một phương pháp thực hiện unit test, hãy thử sử dụng QUnit – một framework được tạo jQuery team và được sử dụng cho dự án jQuery.

Trang chủ và tài liệu: http://docs.jquery.com/Qunit
Mã nguồn dự án: https://github.com/jquery/qunit

Chuẩn bị

Để sử dụng, bạn chỉ cần download hai tập tin sau: qunit.jsqunit.js
Và tạo một file HTML đơn giản có dạng như sau:
01<html>
02<head>
03    <title>QUnit Test Example</title>
04 
05    <link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-git.css" />
06    <script src="http://code.jquery.com/qunit/qunit-git.js"></script>
07</head>
08<body>
09    <div id="qunit"></div>
10 
11    <script>
12    (function(){
13 
14        // your sourcecode goes here
15 
16    })();
17    </script>
18</body>
19</html>
File HTML trên tôi tạo một hàm vô danh (anonymous function) tự động thực thi để chứa các đoạn mã sẽ viết. Phương pháp này được áp dụng phổ biến trong lập trình javascript vì giúp tránh việc tạo ra các định danh không cần thiết, và do đó hạn chế được các trường hợp xung đột (conflict) định danh.
Đừng quên thêm vào thẻ div có id là “qunit”, đây sẽ là nơi để QUnit hiển thị các thông tin và kết quả test lên trên trình duyệt. Nếu bạn mở file này bên trong trình duyệt, bạn sẽ thấy giao diện như sau:
QUnit Test Example - 1

Các tùy chọn

Giao diện QUnit tạo ra có 3 checkbox tùy chọn. Công dụng của chúng là:
- Hide passed tests: ẩn các test chạy đúng. Việc sử dụng tùy chọn có thể khiến bạn khó xác định được test nào fail.
- Check for Globals: test sẽ là fail nếu như một biến global (hay một thuộc tính của đối tượng window) được tạo ra khi thực thi. Việc này nhằm phát hiện và hạn chế việc tạo ra các biến global một cách không cần thiết và có thể gây ảnh hưởng đến toàn bộ trang web.
- No try-catch: Chạy các test mà không sử dụng khối try catch. Tùy chọn này giúp bạn có thể phát hiện các vị trí lỗi và debug (thường kết hợp với tool như Firebug).

Tạo các Unit Test

Trước tiên, tôi tạo một test unit, ở đây là một function add(x, y) đơn giản có chức năng trả về tổng của hai tham số. Sau đó sử dụng hàm test() của QUnit để bắt đầu một unit test mới với hai tham số là tên và đoạn code chứa các mã test:
test( name, expected, test )
Ở đây tôi sử dụng assertion là equal() để so sánh hai giá trị bằng nhau:
equal( actual, expected, message )
01(function(){
02    // test unit
03    function add(x, y){
04        return x + y;
05    }
06 
07    test('add()', function() {
08        equal(add(1, 2), 3, "Passed: 1 + 2 = 3");
09        equal(add(2, null), 3);
10        equal(add_numbers(2, 2), 3);
11 
12    });
13 
14})();
Kết quả:
QUnit Test Example 2
Bạn thấy kết quả hiển thị có thông báo “1 tests of 3 passed, 2 failed“. Bên dưới liệt kê các test có đánh số thứ tự cùng với kết quả của chúng:
1. Passed: 1 + 2 = 3
2. failed (Do giá trị Expected và Result khác nhau)
3. Died (add_numbers không được định nghĩa)
Một test có trạng thái “died” tức là mọi test bên dưới nó sẽ không được thực hiện. Điều này xảy ra khi một lỗi nghiêm trọng có thể ảnh hưởng đến toàn bộ test bên dưới. Bạn cũng có thể tạo ra các test dạng này bằng cách dùng assertion ok():
ok( state, message )
Ví dụ các test unit của bạn cần đối tượng jQuery để chạy, vậy bạn có thể viết như sau:
1test('ok() assertion', function() {
2    ok(jQuery);
3 
4    // assertion calls
5 
6});

Test bất đồng bộ (Asynchronous)

Phương pháp test thông thường sẽ chạy lần lượt từ trên xuống dưới các lời gọi assertion (test đồng bộ – Synchronous). Trong trường hợp muốn test một cách bất đồng bộ, bạn có thể sử dụng hai hàm stop() và start() kết hợp với setTimeout()/setInterval().
- start( decrement ) : Chạy lại test khi nó bị dừng bởi stop().
- stop( increment ) : Dừng test cho đến khi start() được gọi.
Ví dụ:
1test('asynchronous test', function() {
2    stop();
3 
4    equal(1,1);
5    setTimeout(start,1000);
6 
7});
Sẽ có kết quả là:
Tests completed in 1045 milliseconds.
1 tests of 1 passed, 0 failed.
Như bạn thấy, chỉ một lời gọi assertion đơn giản nhưng lại chiếm hơn 1000 milisecond để thực thi. Đó là do dòng lệnh equal(1,1) chỉ được thực hiện sau khi hàm start() được gọi.
YinYangIt’s Blog
(http://yinyangit.wordpress.com/2012/07/11/javascript-unit-test-voi-qunit/)

Thứ Tư, 4 tháng 4, 2012

Browser detect

Copy this script into your JavaScript files. It works immediately, and you can query three properties of the BrowserDetect object:
  • Browser name: BrowserDetect.browser
  • Browser version: BrowserDetect.version
  • OS name: BrowserDetect.OS

var BrowserDetect = {
 init: function () {
  this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
  this.version = this.searchVersion(navigator.userAgent)
   || this.searchVersion(navigator.appVersion)
   || "an unknown version";
  this.OS = this.searchString(this.dataOS) || "an unknown OS";
 },
 searchString: function (data) {
  for (var i=0;i
   var dataString = data[i].string;
   var dataProp = data[i].prop;
   this.versionSearchString = data[i].versionSearch || data[i].identity;
   if (dataString) {
    if (dataString.indexOf(data[i].subString) != -1)
     return data[i].identity;
   }
   else if (dataProp)
    return data[i].identity;
  }
 },
 searchVersion: function (dataString) {
  var index = dataString.indexOf(this.versionSearchString);
  if (index == -1) return;
  return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
 },
 dataBrowser: [
  {
   string: navigator.userAgent,
   subString: "Chrome",
   identity: "Chrome"
  },
  {  string: navigator.userAgent,
   subString: "OmniWeb",
   versionSearch: "OmniWeb/",
   identity: "OmniWeb"
  },
  {
   string: navigator.vendor,
   subString: "Apple",
   identity: "Safari",
   versionSearch: "Version"
  },
  {
   prop: window.opera,
   identity: "Opera",
   versionSearch: "Version"
  },
  {
   string: navigator.vendor,
   subString: "iCab",
   identity: "iCab"
  },
  {
   string: navigator.vendor,
   subString: "KDE",
   identity: "Konqueror"
  },
  {
   string: navigator.userAgent,
   subString: "Firefox",
   identity: "Firefox"
  },
  {
   string: navigator.vendor,
   subString: "Camino",
   identity: "Camino"
  },
  {  // for newer Netscapes (6+)
   string: navigator.userAgent,
   subString: "Netscape",
   identity: "Netscape"
  },
  {
   string: navigator.userAgent,
   subString: "MSIE",
   identity: "Explorer",
   versionSearch: "MSIE"
  },
  {
   string: navigator.userAgent,
   subString: "Gecko",
   identity: "Mozilla",
   versionSearch: "rv"
  },
  {   // for older Netscapes (4-)
   string: navigator.userAgent,
   subString: "Mozilla",
   identity: "Netscape",
   versionSearch: "Mozilla"
  }
 ],
 dataOS : [
  {
   string: navigator.platform,
   subString: "Win",
   identity: "Windows"
  },
  {
   string: navigator.platform,
   subString: "Mac",
   identity: "Mac"
  },
  {
      string: navigator.userAgent,
      subString: "iPhone",
      identity: "iPhone/iPod"
     },
  {
   string: navigator.platform,
   subString: "Linux",
   identity: "Linux"
  }
 ]

};
BrowserDetect.init();
 
(http://www.quirksmode.org/js/detect.html) 

Thứ Ba, 1 tháng 11, 2011

setTimeout & setInterval


setTimeout ( expression, time );
var timeoutId = setTimeout ( expression, time );
clearTimeout ( timeoutId );

setInterval ( expression, time );
var intervalId = setInterval ( expression, time );
clearInterval(intervalId)

Note:
- setTimeout: run one times
- setInterval: loop until call clearInterval

Thứ Năm, 20 tháng 10, 2011

Compress & Encode Javascript

http://javascriptcompressor.com/

Thứ Hai, 10 tháng 10, 2011

Check email is valid

<script type="text/javascript">
function checkEmail() {
var email = document.getElementById('email');
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Hay nhap dia chi email hop le.\nExample@gmail.com');
email.focus;
return false;
}else{
alert('OK roi day, Email nay hop le.');
}
}</script>

(http://www.24kho.com/@forum/threads/4758-Check-Email-Validate-with-Javascript-and-Regular-Expressions-Kiem-tra-tinh-hop-le-cua-email)
Source: http://www.24kho.com/@forum/threads/4758-Check-Email-Validate-with-Javascript-and-Regular-Expressions-Kiem-tra-tinh-hop-le-cua-email#ixzz1aNpsM9Pl

Thứ Ba, 5 tháng 1, 2010

Disable right mouse on web page

<.body oncontextmenu="return false" onselectstart="return false" ondragstart="return false".>

cookie

http://www.w3schools.com/JS/js_cookies.asp


function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
{
alert('Welcome again '+username+'!');
}
else
{
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{
setCookie('username',username,365);
}
}
}

Thứ Năm, 17 tháng 12, 2009

include() with JavaScript

http://www.blogger.com/post-create.g?blogID=6926476941115672672

< type="text/javascript">

function include(file) {
if (document.createElement && document.getElementsByTagName) {
var head = document.getElementsByTagName('head')[0];

var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', file);

head.appendChild(script);
} else {
alert('Your browser can\'t deal with the DOM standard. That means it\'s old. Go fix it!');
}
}

< /script>

To include included.js with the above code just use:

< type="text/javascript">

include('included.js');

< /script>

Thứ Ba, 12 tháng 5, 2009

fix fixed positioning and fixed backgrounds in IE/Win

// fixed.js: fix fixed positioning and fixed backgrounds in IE/Win

// version 1.8, 08-Aug-2003

// written by Andrew Clover <and@doxdesk.com>, use freely


@if (@_win32 && @_jscript_version>4)


var fixed_positions= new Array();

var fixed_backgrounds= new Array();

var fixed_viewport;


// Initialisation. Called when the <body> tag arrives. Set up viewport so the

// rest of the script knows we're going, and add a measurer div, used to detect

// font size changes and measure image sizes for backgrounds later


function fixed_init() {

fixed_viewport= (document.compatMode=='CSS1Compat') ?

document.documentElement : document.body;

var el= document.createElement('div');

el.setAttribute('id', 'fixed-measure');

el.style.position= 'absolute';

el.style.top= '0'; el.style.left= '0';

el.style.overflow= 'hidden'; el.style.visibility= 'hidden';

el.style.fontSize= 'xx-large'; el.style.height= '5em';

el.style.setExpression('width', 'fixed_measureFont()');

document.body.insertBefore(el, document.body.firstChild);

}


// Binding. Called every time an element is added to the document, check it

// for fixed features, if found add to our lists and set initial props


function fixed_bind(el) {

var needLayout= false;

var tag= el.tagName.toLowerCase();

var st= el.style;

var cst= el.currentStyle;

var anc;


// find fixed-position elements

if (cst.position=='fixed') {

needLayout= true;

fixed_positions[fixed_positions.length]= el;

// store original positioning as we'll overwrite it

st.position= 'absolute';

st.fixedPLeft= cst.left;

st.fixedPTop= cst.top;

st.fixedPRight= cst.right;

st.fixedPBottom= cst.bottom;

st.fixedPWidth= fixed_parseLength(cst.width);

st.fixedPHeight= fixed_parseLength(cst.height);

// find element that will act as containing box, for convenience later

st.fixedCB= null;

for (anc= el; (anc= anc.parentElement).parentElement;) {

if (anc.currentStyle.position!='static') {

st.fixedCB= anc;

break;

} }

// detect nested fixed positioning (only ancestor need move)

st.fixedNest= false;

for (anc= el; anc= anc.parentElement;) {

if (anc.style.fixedNest!=null)

st.fixedNest= true;

break;

}

}


// find fixed-background elements (not body/html which IE already gets right)

if (cst.backgroundAttachment=='fixed' && tag!='body' && tag!='html') {

needLayout= true;

fixed_backgrounds[fixed_backgrounds.length]= el;

// get background offset, converting from keyword if necessary

st.fixedBLeft= fixed_parseLength(cst.backgroundPositionX);

st.fixedBTop= fixed_parseLength(cst.backgroundPositionY);

// if it's a non-zero %age, need to know size of image for layout

if (st.fixedBLeft[1]=='%' || st.fixedBTop[1]=='%') {

st.fixedBWidth= 0; st.fixedBHeight= 0;

fixed_measureBack(el);

}

}

if (needLayout) fixed_layout();

}


// Layout. On every window or font size change, recalculate positioning


// Request re-layout at next free moment

var fixed_delaying= false;

function fixed_delayout() {

if (fixed_delaying) return;

fixed_delaying= true;

window.setTimeout(fixed_layout, 0);

}


var fixed_ARBITRARY= 200;


function fixed_layout() {

fixed_delaying= false;

if (!fixed_viewport) return;

var i, el, st, j, pr, tmp, A= 'auto';

var cb, cbLeft, cbTop, cbRight, cbBottom, oLeft, oTop, oRight, oBottom;

var vpWidth=fixed_viewport.clientWidth, vpHeight=fixed_viewport.clientHeight;


// calculate initial position for fixed-position elements [black magic]

for (i= fixed_positions.length; i-->0;) {

el= fixed_positions[i]; st= el.style;

// find positioning of containing block

cb= st.fixedCB; if (!cb) cb= fixed_viewport;

cbLeft= fixed_pageLeft(cb); cbTop= fixed_pageTop(cb);

if (cb!=fixed_viewport) { cbLeft+= cb.clientLeft; cbTop+= cb.clientTop; }

cbRight= fixed_viewport.clientWidth-cbLeft-cb.clientWidth;

cbBottom= fixed_viewport.clientHeight-cbTop-cb.clientHeight;

// if size is in %, must recalculate relative to viewport

if (st.fixedPWidth[1]=='%')

st.width= Math.round(vpWidth*st.fixedPWidth[0]/100)+'px';

if (st.fixedPHeight[1]=='%')

st.height= Math.round(vpHeight*st.fixedPHeight[0]/100)+'px';

// find out offset values at max size, to account for margins

st.left= A; st.right= '0'; st.top= A; st.bottom= '0';

oRight= el.offsetLeft+el.offsetWidth; oBottom= el.offsetTop+el.offsetHeight;

st.left= '0'; st.right= A; st.top= '0'; st.bottom= A;

oLeft= el.offsetLeft; oTop= el.offsetTop;

// use this to convert all edges to pixels

st.left= A; st.right= st.fixedPRight;

st.top= A; st.bottom= st.fixedPBottom;

oRight-= el.offsetLeft+el.offsetWidth;

oBottom-= el.offsetTop+el.offsetHeight;

st.left= st.fixedPLeft; st.top= st.fixedPTop;

oLeft= el.offsetLeft-oLeft; oTop= el.offsetTop-oTop;

// edge positioning fix

if (st.fixedPWidth[1]==A && st.fixedPLeft!=A && st.fixedPRight!=A) {

tmp= el.offsetLeft; st.left= A; st.width= fixed_ARBITRARY+'px';

tmp= fixed_ARBITRARY+el.offsetLeft-tmp+cbLeft+cbRight;

st.left= st.fixedPLeft; st.width= ((tmp<1)?1:tmp)+'px';

}

if (st.fixedPHeight[1]==A && st.fixedPTop!=A && st.fixedPBottom!=A) {

tmp= el.offsetTop; st.top= A; st.height= fixed_ARBITRARY+'px';

tmp= fixed_ARBITRARY+el.offsetTop-tmp+cbTop+cbBottom;

st.top= st.fixedPTop; st.height= ((tmp<1)?1:tmp)+'px';

}

// move all non-auto edges relative to the viewport

st.fixedCLeft= (st.fixedPLeft=='auto') ? oLeft : oLeft-cbLeft;

st.fixedCTop= (st.fixedPTop=='auto') ? oTop : oTop-cbTop;

st.fixedCRight= (st.fixedPRight=='auto') ? oRight : oRight-cbRight;

st.fixedCBottom= (st.fixedPBottom=='auto') ? oBottom : oBottom-cbBottom;

// remove left-positioning of right-positioned elements

if (st.fixedPLeft=='auto' && st.fixedPRight!='auto') st.fixedCLeft= 'auto';

if (st.fixedPTop=='auto' && st.fixedPBottom!='auto') st.fixedCTop= 'auto';

}


// calculate initial positioning of fixed backgrounds

for (i= fixed_backgrounds.length; i-->0;) {

el= fixed_backgrounds[i]; st= el.style;

tmp= st.fixedBImage;

if (tmp) {

if (tmp.readyState!='uninitialized') {

st.fixedBWidth= tmp.offsetWidth;

st.fixedBHeight= tmp.offsetHeight;

st.fixedBImage= window.undefined;

}

}

st.fixedBX= fixed_length(el, st.fixedBLeft, vpWidth-st.fixedBWidth);

st.fixedBY= fixed_length(el, st.fixedBTop, vpHeight-st.fixedBHeight);

}


// now call scroll() to set the positions from the values just calculated

fixed_scroll();

}


// Scrolling. Offset fixed elements relative to viewport scrollness


var fixed_lastX, fixed_lastY;

var fixed_PATCHDELAY= 300;

var fixed_patching= false;


// callback function after a scroll, because incorrect scroll position is

// often reported first go!

function fixed_patch() {

fixed_patching= false;

var scrollX= fixed_viewport.scrollLeft, scrollY= fixed_viewport.scrollTop;

if (scrollX!=fixed_lastX && scrollY!=fixed_lastY) fixed_scroll();

}


function fixed_scroll() {

if (!fixed_viewport) return;

var i, el, st, viewportX, viewportY;

var scrollX= fixed_viewport.scrollLeft, scrollY= fixed_viewport.scrollTop;

fixed_lastX= scrollX; fixed_lastY= scrollY;


// move non-nested fixed-position elements

for (i= fixed_positions.length; i-->0;) {

st= fixed_positions[i].style;

viewportX= (st.fixedNest) ? 0 : scrollX;

viewportY= (st.fixedNest) ? 0 : scrollY;

if (st.fixedCLeft!='auto') st.left= (st.fixedCLeft+viewportX)+'px';

if (st.fixedCTop!='auto') st.top= (st.fixedCTop+viewportY)+'px';

viewportX= (st.fixedCB==null || st.fixedCB==fixed_viewport) ? 0 : viewportX;

viewportY= (st.fixedCB==null || st.fixedCB==fixed_viewport) ? 0 : viewportY;

st.right= (st.fixedCRight-viewportX+1)+'px'; st.right= (st.fixedCRight-viewportX)+'px';

st.bottom= (st.fixedCBottom-viewportY+1)+'px'; st.bottom= (st.fixedCBottom-viewportY)+'px';

}


// align fixed backgrounds to viewport

for (i= fixed_backgrounds.length; i-->0;) {

el= fixed_backgrounds[i]; st= el.style;

viewportX= scrollX;

viewportY= scrollY;

while (el.offsetParent) {

viewportX-= el.offsetLeft+el.clientLeft;

viewportY-= el.offsetTop +el.clientTop;

el= el.offsetParent;

}

st.backgroundPositionX= (st.fixedBX+viewportX)+'px';

st.backgroundPositionY= (st.fixedBY+viewportY)+'px';

}


// call back again in a tic

if (!fixed_patching) {

fixed_patching= true;

window.setTimeout(fixed_patch, fixed_PATCHDELAY);

}

}


// Measurement. Load bg-image into an invisible element on the page, when

// loaded write the width/height to an element's style for layout use; detect

// when font size changes


function fixed_measureBack(el) {

var measure= document.getElementById('fixed-measure');

var img= document.createElement('img');

img.setAttribute('src', fixed_parseURL(el.currentStyle.backgroundImage));

measure.appendChild(img);

el.style.fixedBImage= img;

if (img.readyState=='uninitialized')

img.attachEvent('onreadystatechange', fixed_measureBackImage_ready);

}


function fixed_measureBackImage_ready() {

var img= event.srcElement;

if (img && img.readyState!='uninitialized') {

img.detachEvent('onreadystatechange', fixed_measureBackImage_ready);

fixed_layout();

}

}


var fixed_fontsize= 0;

function fixed_measureFont() {

var fs= document.getElementById('fixed-measure').offsetHeight;

if (fixed_fontsize!=fs && fixed_fontsize!=0)

fixed_delayout();

fixed_fontsize= fs;

return '5em';

}


// Utility. General-purpose functions


// parse url() to get value inside


function fixed_parseURL(v) {

v= v.substring(4, v.length-1);

if (v.charAt(0)=='"' && v.charAt(v.length-1)=='"' ||

v.charAt(0)=="'" && v.charAt(v.length-1)=="'")

return v.substring(1, v.length-1);

else return v;

}


// parse length or auto or background-position keyword into number and unit


var fixed_numberChars= '+-0123456789.';

var fixed_ZERO= new Array(0, 'px');

var fixed_50PC= new Array(50, '%');

var fixed_100PC= new Array(100, '%');

var fixed_AUTO= new Array(0, 'auto');


function fixed_parseLength(v) {

var num, i;

if (v=='left' || v=='top') return fixed_ZERO;

if (v=='right' || v=='bottom') return fixed_100PC;

if (v=='center') return fixed_50PC;

if (v=='auto') return fixed_AUTO;

i= 0;

while (i<v.length && fixed_numberChars.indexOf(v.charAt(i))!=-1)

i++;

num= parseFloat(v.substring(0, i));

if (num==0) return fixed_ZERO;

else return new Array(num, v.substring(i));

}


// convert parsed (number, unit) into a number of pixels


function fixed_length(el, l, full) {

var tmp, x;

if (l[1]=='px') return l[0];

if (l[1]=='%') return Math.round(full*l[0]/100);

// other units - measure by setting position; this is rather inefficient

// but then these units are used for background-position so seldom...

tmp= el.currentStyle.left;

el.style.left= '0';

x= el.offsetLeft;

el.style.left= l[0]+l[1];

x= el.offsetLeft-x;

el.style.left= tmp;

return x;

}


// convert stupid IE offsetLeft/Top to page-relative values


function fixed_pageLeft(el) {

var v= 0;

while (el.offsetParent) {

v+= el.offsetLeft;

el= el.offsetParent;

}

return v;

}

function fixed_pageTop(el) {

var v= 0;

while (el.offsetParent) {

v+= el.offsetTop;

el= el.offsetParent;

}

return v;

}


// Scanning. Check document every so often until it has finished loading. Do

// nothing until <body> arrives, then call main init. Pass any new elements

// found on each scan to be bound


var fixed_SCANDELAY= 500;


function fixed_scan() {

if (!document.body) return;

if (!fixed_viewport) fixed_init();

var el;

for (var i= 0; i<document.all.length; i++) {

el= document.all[i];

if (!el.fixed_bound) {

el.fixed_bound= true;

fixed_bind(el);

} }

}


var fixed_scanner;

function fixed_stop() {

window.clearInterval(fixed_scanner);

fixed_scan();

}


fixed_scan();

fixed_scanner= window.setInterval(fixed_scan, fixed_SCANDELAY);

window.attachEvent('onload', fixed_stop);

window.attachEvent('onresize', fixed_delayout);

window.attachEvent('onscroll', fixed_scroll);


@end

Thứ Hai, 27 tháng 4, 2009

Using Multiple JavaScript Onload Functions

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
/* more code to run on page load */
});