March 26, 2009

JSONP

JSONP:
//get Data cross domain
<img src="binary">
<Iframe src="HTML">
<script src="javascript">

March 25, 2009

Basic Ajax

//Ajax is possible to return responseXML(Content-type: text/xml), responseText(raw text)

//Any status in the 200 range is good
( xmlHttp.status >= 200 && xmlHttp.status < 300 ) ||
// Successful if the document has not been modified
xmlHttp.status == 304 ||


xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET","http://www.google.com",true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function(){
if ( xmlHttp.readyState == 4 ) {
document.getElementById('display').innerHTML=xmlHttp.responseText;
console.log(xmlHttp.getResponseHeader("content-type"));
console.log(xmlHttp.status)
}
};
--------------------------------------------
//Ajax with Timeout
var timeoutLength = 5000;
var requestDone = false;
setTimeout(function(){requestDone = true;}, timeoutLength);

xmlHttp.send(null);
xmlHttp.onreadystatechange = function(){
if ( xmlHttp.readyState == 4 && !requestDone ) {
document.getElementById('display').innerHTML=xmlHttp.responseText;
}
};

March 24, 2009

Javascript Image slideShow


//set div to display in the middle of the screen even it's scrolled

div.style.top = window.pageYOffset + (screen.height/2) - (parseInt(div.style.height)/2) + "px";
----------------------------------------
function windowHeight() {
var de = document.documentElement;
return self.innerHeight || ( de && de.clientHeight ) || document.body.clientHeight;
}
function windowWidth() {
var de = document.documentElement;
return self.innerWidth || ( de && de.clientWidth ) || document.body.clientWidth;
}

function getWidth( elem ) {
return parseInt( getStyle( elem, 'width' ) );
}

function getHeight( elem ) {
return parseInt( getStyle( elem, 'height' ) );
}

function pageHeight() {
return document.body.scrollHeight;
}

function pageWidth() {
return document.body.scrollWidth;
}

function scrollX() {
var de = document.documentElement;
return self.pageXOffset || ( de && de.scrollLeft ) || document.body.scrollLeft;
}

function scrollY() {
var de = document.documentElement;
return self.pageYOffset || ( de && de.scrollTop ) || document.body.scrollTop;
}

function setX(elem, pos) {
elem.style.left = pos + "px";
}

function setY(elem, pos) {
elem.style.top = pos + "px";
}

function addX(elem,pos) {
setX( posX(elem) + pos );
}

function addY(elem,pos) {
setY( posY(elem) + pos );
}

function hide( elem ) {
var curDisplay = getStyle( elem, 'display' );
if ( curDisplay != 'none' )
elem.$oldDisplay = curDisplay;
elem.style.display = 'none';
}

function show( elem ) {
elem.style.display = elem.$oldDisplay || '';
}

function hideOverlay() {
curImage = null;
hide( document.getElementById("overlay") );
hide( document.getElementById("gallery") );
}

function showOverlay() {
var over = document.getElementById("overlay");
over.style.height = pageHeight() + "px";
over.style.width = pageWidth() + "px";
fadeIn( over, 50, 10 );
}
//--------------------------------------------------------------
function showImage(cur) {
curImage = cur;
var img = document.getElementById("gallery_image");
if ( img.firstChild )
img.removeChild( img.firstChild );
img.appendChild( cur.firstChild.cloneNode( true ) );
//id("gallery_title").innerHTML = cur.firstChild.firstChild.alt;
var gallery = document.getElementById("gallery");
gallery.className = cur.className;
fadeIn( gallery, 100, 10 );
adjust();
}
function adjust(){
var obj = document.getElementById("gallery");
if ( !obj ) return;
var w = getWidth( obj );
var h = getHeight( obj );
var t = scrollY() + ( windowHeight() / 2 ) - ( h / 2 );
if ( t < 0 ) t = 0;
var l = scrollX() + ( windowWidth() / 2 ) - ( w / 2 );
if ( l < 0 ) l = 0;
setY( obj, t );
setX( obj, l );
};

function prevImage() {
showImage( prev( curImage ) );
return false;
}

function nextImage() {
showImage( next( curImage ) );
return false;
}

function startShow(obj) {
var elem = obj.getElementsByTagName('li');
var gallery = document.getElementById("gallery");
for ( var i = 0; i < elem.length; i++ ) new function() {
var cur = elem[i];
setTimeout(function(){
showImage( cur );
setTimeout(function(){
fadeOut( gallery, 0, 10 );
}, 3500 );
}, i * 5000 );
};
setTimeout( hideOverlay, 5000 * elem.length );
showOverlay();
}

March 23, 2009

Javascript feature functions & properties


//Browser size:
document.body.scrollHeight;
document.body.scrollWidth;
----------------------------------------------------------
// get Left and Top of an element:
e = e || window.event;
return e.pageX || e.clientX + document.body.scrollLeft;
return e.pageY || e.clientY + document.body.scrollTop;
----------------------------------------------------------
function hide( elem ) {
var curDisplay = getStyle( elem, 'display' );
if ( curDisplay != 'none' )
elem.$oldDisplay = curDisplay;
elem.style.display = 'none';
}
function show( elem ) {
elem.style.display = elem.$oldDisplay || '';
}
----------------------------------------------------------
// Slide Element down
function slideDown(elem){
elem.style.height = '0px';
elem.style.display = 'block';
var h = document.body.scrollHeight;
for ( var i = 0; i <= 100; i += 5 ) {
(function(){
var pos = i;
setTimeout(function(){
elem.style.height = (( pos / 100 ) * h ) + "px";
},( pos + 1 ) * 10 );
})();
}
}
----------------------------------------------------------
function setOpacity( elem, level ) {
if ( elem.filters )
elem.style.filters = 'alpha(opacity=' + level + ')';
else
elem.style.opacity = level / 200;
}

function fadeIn( elem ) {
setOpacity( elem,0);
// elem.style.display = elem.$oldDisplay || '';
elem.style.display = "block";
for ( var i = 0; i <= 100; i += 5 ) {
(function(){
var pos = i ;
setTimeout(function(){
setOpacity( elem, pos );
}, ( pos + 1 ) * 10 );
})();
}
}

function fadeOut( elem ) {
var j = 0;
for ( var i = 100; i > 0; i -= 5 ) {
j +=5;
(function(){
var pos = i ;
setTimeout(function(){
setOpacity( elem, pos);
if(pos <= 5){
elem.style.display = "none";
}
}, (j+1) * 5);
})();
}
}

March 18, 2009

Javascript Validation expression


Validate an Email address:
/^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/.test("http://www.google.com")

Validate a URL:
/^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test('abc@yahoo.com')

Validate a phone number:
/(\d{3}).*(\d{3}).*(\d{4})/.exec('1232344567') => 1232344567 123 234 4567

Validate a date:
/^\d{2}\/\d{2}\/\d{2,4}$/.test('12/32/1231')

//Change these 4 condition into JSON object
--------------------------------------------------------------------

var errMsg = {
required: {
msg: "This field is required.",
test: function(obj,load) {
return obj.value.length > 0 || load || obj.value == obj.defaultValue;
}
},
email: {
msg: "Not a valid email address.",
test: function(obj) {
return !obj.value ||
/^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test( obj.value );
}
},
phone: {
msg: "Not a valid phone number.",
test: function(obj) {
var m = /(\d{3}).*(\d{3}).*(\d{4})/.exec( obj.value );
if ( m ) obj.value = "(" + m[1] + ") " + m[2] + "-" + m[3];
return !obj.value || m;
}
},
date: {
msg: "Not a valid date.",
test: function(obj) {
return !obj.value || /^\d{2}\/\d{2}\/\d{2,4}$/.test(obj.value);
}
},
url: {
msg: "Not a valid URL.",
test: function(obj) {
return !obj.value || obj.value == 'http://' ||
/^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/.test( obj.value );
}}};

errMsg['email'].test('234@yahoo.com');

/*for(name in errMsg){
console.log(name);
for(tempname in errMsg[name]){
console.log(tempname);
}
}*/

March 12, 2009

get any style attributes from your element


//elem = element( document.getElementsByTagName("font")[0].childNodes[2]), name = name of style's attribute( height, width)
function getStyle( elem, name ) {
if (elem.style[name])
return elem.style[name];
else if (elem.currentStyle)
return elem.currentStyle[name];
else if (document.defaultView && document.defaultView.getComputedStyle) {
name = name.replace(/([A-Z])/g,"-$1");
name = name.toLowerCase();
var s = document.defaultView.getComputedStyle(elem,"");
return s && s.getPropertyValue(name);

} else
return null;
}

To apply stylesheet when Javascript is not enabled

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<!--The instant the script is run, a new class is attached to the <html> element
giving us the ability to know if JavaScript is enabled, or not.-->
<script>document.documentElement.className = "js";</script>
<!--If JavaScript is enabled, hide the block of text,
which we will fade in later.-->
<style>.js #fadein { display: none }</style>
</head>
<body>
<div id="fadein">Block of stuff to fade in...</div>
</body>
</html>

March 11, 2009

Stop Default Browser Action

A Generic Function for Preventing the Default Browser Action from Occurring
======================================

function stopDefault( e ) {
// Prevent the default browser action (W3C)
if ( e && e.preventDefault )
e.preventDefault();
// A shortcut for stoping the browser action in IE
else
window.event.returnValue = false;
return false;
}

Capturing and Bubbling in Javascript

Normally in Javascript, whenever you apply stylesheet to any parents which containe many elements, those stylesheets will effect to all elements and their parents but we can use stopBubble() to prevent this problem.
======================================
function stopBubble(e) {
if ( e && e.stopPropagation )
e.stopPropagation();
else
window.event.cancelBubble = true;
}
-----------------------------------------------------------------
Using stopBubble() to Create an Interactive Set of Elements
var all = document.getElementsByTagName("*");
for ( var i = 0; i < all.length; i++ ) {
all[i].onmouseover = function(e) {
this.style.border = "1px solid red";
stopBubble( e );
};
all[i].onmouseout = function(e) {
this.style.border = "0px";
stopBubble( e );
};
}

March 10, 2009

My first javascript with DOM

parentNode, childNodes, nodeValue, nodeName, nodeType, firstChild, lastChild, nextChild, previousSibling, nextSibling
- nodeType (Element = 1, Attribute = 2, Text = 3, Comment = 8, Document = 9)
-----------------------------------------------------------
createElement, insertBefore, appendChild, removeChild, getAttribute, setAttribute
===========================================================

for(var i = 0; i < center.length; i++){
console.log(center[i].nodeName);
var child_node = center[i].childNodes;
//console.log(center[i].innerHTML);
for(var j = 0; j < child_node.length; j++){
//console.log(child_node[j].nodeName);
if(child_node[j].nodeName =='A'){
console.log(child_node[j].innerHTML);
console.log(child_node[j].getAttribute('href'));
}
}
}
-----------------------------------------------------------
var temp = document.getElementsByTagName("font");
var element = document.createElement('<a>');
element.innerHTML="samneang";
element.setAttribute('href','http://samneang-ngeth.blogspot.com');
temp[0].appendChild(element);
temp[0].removeChild(temp[0].lastChild);