Was helping an friend on some JavaScript code. was using yui-dom-event and same code was working differently on ie and ff. since I was helping remotely I couldn’t guess more out of it. Finally after 1 day of full calls and chats finally asked him to expose the url. finally figured some html tags were being closed improperly. so moral of the story is, “if your well known library behaving weirdly in different browsers first thing you should look at is, generated html source”.
December 7, 2010
February 3, 2010
Simple Ajax-PHP File Browser using PHP and YUI.
This example is to show how you will create a simple file browser in PHP, and get it working with YUI. Once you deploy it inside your web server it should look like this.
Download Simple Ajax-PHP File Browser here.
January 9, 2010
December 11, 2009
difference between window.onload and document.ready
It’s pretty simple but people tend to forget.
Major bugbeer for javascript developers is non-availability of DOM for javascript execution, if you are including javascript inside <head> tag this is the common situation. window.onload solved this problem. if you callback a function on window.onload that function gets called after page loading completed. Here the problem is javascript execution needs to wait till all CSS and images gets loaded. Hence came the DOMContentLoaded. Most browsers trigger this event when they are ready for javascript execution, this event gets fire before window.onload
all javascript libraries provide hooks to this event,
in jquery
$(document).ready(function() { // put all your jQuery goodness in here. });
in yui 2.x
YAHOO.util.Event.onDOMReady(function() { domReady = true; alert('Dom is Ready'); });
October 28, 2009
YUI Tab and Flash Graph/Movie
when you use YUI Tab with flash graphs/movie in them, firefox refresh the movie every time you switch away and back to the tab containing flash Graph. if you are using simple graphs it’s not noticeable, but in big movies/graphs it’s irritating. I figured out the basic problem is whenever you change position / overflow values of a div, firefox reloads all flash movies within that div. YUI Tabview have these 2 properties defined for .yui-navset .yui-content .yui-hidden class which get appended to content div when they get hidden.
Fix is to add same properties to visible tab-content div also. This doesn’t make any harm in the way Tab works. Here is the css I did add to fix this issues. But I have not tested this on browsers other than Firefox, try yourself.
.yui-navset .yui-content > div {overflow:hidden;position:static;}
.yui-navset .yui-content .yui-hidden {position:static; }
October 12, 2009
Asynchronous Javascript + XML
Ajax or Asynchronous Javascript + XML started with Jesse James Garrett penning an online article on usage of XHR aka XMLHttpRequest object in 2005. Idea behind Ajax was to give user data/page updates without refreshing the page. By Doing so Ajax made static boring HTML pages to be highly interactive and exciting. Later on developers and designers around the world came up with enhanced use cases and patterns for using Ajax. Prior to XHR object ajax kind of functionality was being achieved using lot many hacks, mostly involving hidden frames or iframes, Java Applets and Flash movie. XHR introduced streamlined interface for making server requests and evaluating responses. Despite having XML in it’s name Ajax is format-agnostic; the technique basically is about retrieving data from server without refreshing page.
Microsoft first introducing this functionality in IE5, later an other browsers started implementing and Ajax was the buzz word in late 2005 and early 2006. IE browsers before IE 7 needed using one of MSXML2.XMLHttp , MSXML2.XMLHttp.3.0 , and MXSML2.XMLHttp.6.0 to be used in order to create XHR object, code for creating XHR object in browser < IE 7 looks like this.
function createXHR(){
if(typeof arguments.callee.activeString != "string"){
var versions = ["MXSML2.XMLHttp.6.0", "MXSML2.XMLHttp.3.0","MXSML2.XMLHttp"];
for(var i=0, len = versions.length; i<len;i++ ){
try{
var xhr = new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
return xhr;
}catch (ex){
//skip
}
}
}
return new ActiveXObject (arguments.callee.activeXString);
}
IE 7, Firefox, Opera, Chrome and Safari all support a native XHR object that can be created using,
var xhr = new XMLHttpRequest();
if you need to support you first check for XMLHttpRequest support, if supported return that object else continue with above mentioned function.
XHR object usage looks like this.
var xhr = new XMLHttpRequest();
xhr.open("get","yourdata.php", false); // arguments in order HTTP method, url, asynchronous true/false;
xhr.send(null)
if you pass third argument asynchronous as false, you are making and synchronous server call, javascript execution wait till server respond with result. when the response is received XHR object will have result assigned to it’s properties as follows:
responseText – Text in body of the response
responseXML - Contains XML DOM document with response data if the response has content type set to "text/xml" or "application/xml"
status – HTTP status of the request
statusText – Description of HTTP status.
Where are setting third argument asynchronous as true will allow you to make asynchronous call, which doesn’t halt javascript execution till the request is completed. but you need to check readyStage of XHR object to track status of the request, readyState can have following possible values
0 – Un-initialized
1 – Initialized but not called send()
2 – Sent, send() called
3 – Receiving, partial response is received
4 – Complete, received complete response
whenever ready state changes from one to another readystatechange event gets fired, adding a listener/function to this event will let you track status of the XHR request.
// ready state tracked code looks like this
var xhr = createXHR();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
if ((xhr.status > = 200 & & xhr.status < 300) || xhr.status == 304){
alert(xhr.responseText);
} else {
alert(“Request was unsuccessful: “ + xhr.status);
}
}
};
xhr.open(“get”, “example.txt”, true);
xhr.send(null); ((
// you can cancel an asynchronous request by using xhr.abort();
October 5, 2009
DOM
DOM, Document Object Model for XML that extended to be used in HTML. In XML and HTML Document consist hierarchy of nodes with different types of data. DOM allows unprecedented control over web pages. Nodes can be added, removed, replaced and modified easily.
DOM Core was the API developed to handle XML documents, DOM HTML extended DOM Core by adding HTML specific objects and methods. DOM is not JavaScript specific, it is implemented in numerous other languages as well, where as DOM for web implemented using ECMAScript, and makes up to large part of JavaScript.
Idea behind W3C developing DOM Level 1 (1998) was to map structure of a document. Aims of DOM Level 2 was much broader including support for events, range, traversal of document, and support for CSS. Level 1 also extended to support XML namespaces.
Following new modules were introduced in DOM Level 2
DOM Event
DOM Style
DOM Views
DOM Range and Traversal
DOM 3 further extend DOM to introduces methods to Load and Save documents in uniform way, and also methods to validate DOM
DOM, Document Object Model for XML that extended to be used in HTML. In XML and HTML Document consist hierarchy of nodes with different types of data. DOM allows unprecedented control over web pages. Nodes can be added, removed, replaced and modified easily.
DOM, Document Object Model for XML that extended to be used in HTML. In XML and HTML Document consist hierarchy of nodes with different types of data. DOM allows unprecedented control over web pages. Nodes can be added, removed, replaced and modified easily.
DOM Core was the API developed to handle XML documents, DOM HTML extended DOM Core by adding HTML specific objects and methods. DOM is not JavaScript specific, it is implemented in numerous other languages as well, where as DOM for web implemented using ECMAScript, and makes up to large part of JavaScript.
Idea behind W3C developing DOM Level 1 (1998) was to map structure of a document. Aims of DOM Level 2 was much broader including support for events, range, traversal of document, and support for CSS. Level 1 also extended to support XML namespaces.
Following new modules were introduced in DOM Level 2
- DOM Event
- DOM Style
- DOM Views
- DOM Range and Traversal
DOM 3 further extend DOM to introduce methods to Load and Save documents in uniform way, and also methods to validate DOM
September 26, 2009
Prototype Chains
Whenever you try to access some property of a JavaScript object, it will look for that property in 2 places. First one is Object itself and second one is Object’s prototype. If prototype of that Object is another Object then search moves on that Object and that Object’s prototype. Search like this carried till it reach that accessed property to return value or native JavaScript Object, of which prototype is nothing but null and returns null. this feature of JavaScript is called as Prototype Chains
Objects in javaScript
An Object in JavaScript is a collection of un-ordered properties each of which contains a primitive value, object or function.
Simplest way of creating object is creating new instance of Object and add properties into it.
Example:
var pet = new Object()
pet.name = "Dev";
pet.age = 2;
pet.type = "dog"
pet.whatPet = function(){
alert(this.type);
}
But when you have to create many instances of a given object you need to use lot many redundant code. Hence to avoid programmers started introducing Factory pattern to create new objects.
Factory pattern is popular design-pattern which is used to abstract away process of creating specific objects.
Pet class creation code with Factory pattern looks like this.
function createPet(name, age,type){
var o = new Object();
o.name = name;
o.age = age;
o.type = type;
o.whatPet=function(){
alert(this.type);
}
return o;
}
var dog1= createPet("Dev",2,"dog");
var cat1= createPet("Cuty",1,"cat");
Using this method will soft problem of redundancy but by this way we cannot identify type of an object. This problem was again resolved using Constructor pattern.
function Pet(name, age,type){
this.name = name;
this.age = age;
this.type = type;
this.whatPet=function(){
alert(this.type);
}
}
var dog1= new Pet ("Dev",2,"dog");
A constructor function defers from normal function just in the way it is called, otherwise syntax remains same for both the functions. Constructor function can be called as follows:
var dog1 = new Pet ("Dev",2,"dog");
dog1.whatPet();
//or calling it like functions
Pet("Dev",2,"dog");
window.whatPet();
// all objects reside in global context can be referred by window.
var o = new Object();
Pet.call(o,"Dev",2,"dog");
o.whatPet();
Only problem with constructor is whatever methods you define they won’t share same instance of functions. Each instance of given object with create its own function instance for each method. There is no point in having multiple instances of the same Function.
to be continued…
September 20, 2009
Things to Remember about JavaScript
About <script> element
- language attribute is deprecated and should not be used.
- defer attribute not supported by all browsers
- using “<” in script within a XHTML throws syntax error, you should use CDATA directive
- type attribute should set to “text/javascript” to maximize browser comapatability
- using “</script>” anywhere in the script brakes code execution, if you happen to use you can use “</scri”+”pt>”
- external JavaScript inclusion looks like “< script type=”text/javascript” src=”example1.js” > < /script >”
- use
< script > < !–function sayHi(){alert(“Hi!”);}//– > < /script >
< script > < !– and //– > < /script > to make sure, non-JavaScript browsers don’t display JavaScript as body content.
Inline V/s External scripts:
External scripts provide following better maintainability and caching benefits