Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,153,941 members, 7,821,297 topics. Date: Wednesday, 08 May 2024 at 11:06 AM

Advanced Javascript Stunts - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / Advanced Javascript Stunts (1161 Views)

Trouble With Javascript Code / Dhtml Quiz: How Will You Detect If A Browser Support Javascript From Php Code? / Creating Complex / Advanced Search Forms With Sql Queries In Dreamweaver (2) (3) (4)

(1) (Reply) (Go Down)

Advanced Javascript Stunts by cdeveloper(m): 5:19pm On May 26, 2009
Wondering what the heck this chap is up to, well i am JS Freak and i want to look at some stunts that can be done in JS. I will list then here and gradually fill them in.So if you know some stunts yourself, this the time to show it off.
1. How do I perform Cross Domain Request with JavaScript
2. How do i Create an Auto Grow Textarea Box
3. How do I preload Images before showing them in a Page
4. How do i Store data on the clientside with JavaScript
5. How do i upload files to a server without page refresh with JavaScript
6. How do i implement a class in JavaScript(is that possible?)
7.  how do i implement private and public properties and methods in JavaScript

Seven Interesting "How Do I's":
1 . How do i perform cross domain request with javascript
Well for the first one anyone who has worked with Ajax will agree that it is not possible to contact a different domain from which your js scripts was served from the clientside.This Internet GUys call it "Same Origin Policies" that is implemented in the browser for security reasons, but clever dudes have come up with a way to do that. This is the genesis of what is today called MashUps, Google MashUps,Yahoo MashUps blah blah blah. The idea is that you can serve scripts from www.mydomain.com and still be able to load up data from www.yourdomain.com from the clientside. This is normally done on the serverside via server-to-server communication. But This days the forgotten language(JavaScript) has hit the limelight again with the advent of Ajax technigues,JSON( JavaScript Object Notation) a kind of data interchange format.
to illustrate this concept look at the codes below:

<head>
<script type='text/javascript'>
function loadData(url,params)
{
   var params=params || {};
   var html=[];
   if(params.length>0)
  {
      for(var k in params)
      {
            html.push(k+"="+params[k]);
      }
     
     url=url+"?"+html.join("&"wink;
     url=url+"&callback=processResponse";
  }

    var script=document.createElement("script"wink;
          script.type='text/javascript';
          script.src=url;
          document.getElementsByTagName("head"wink[0].appendChild(script);

}

function processResponse(data)
{
     if(data.name){alert("the server returned "+data.name+""wink;}
}
</script>
</head>

and that is the technique for cross domain request. the returned data is in JSON format. The url sent to this server conatins parameters and a callback function that the server will pass the data to. Once the server passes the data to the callback function it will be executed on the clientside by the callback function "processResponse": the server script might look like this in PHP

<?php

  $param1=$_GET["param1"];
  $callback=$_GET["callback"];

  //do some processing that will return data as an array
  //convert it to json and call the callback function

  $data=array("name"=>"Ama"wink;
  $jsonData=json_encode($data);

    echo $callback."(".jsonData."wink";
   exit
?>

this will send the json encoded data to processResponse, and it will handle json data. Note that you need to ensure that the json_encode function is enabled in the server configuration.
This is the idea that is used by sites like Flickr etc to sent data across domains and you can communicate with these server from your clientside with pure JavaScript. JSON has revolutionized the way data is exchanged on the web this days and that comes security problems as well
Re: Advanced Javascript Stunts by Nobody: 10:28am On May 27, 2009
I know all them stunts, try me, i can even do them with my eyes closed sef! And, i even wrote a json based chat some months ago too. . .

Lemme find some proofs first. . .

So check this one out on my site for upload: http://mwebng.net/demos/jupload/

json chat: i cant remember where the thread is: but the free demo(sosurce code) can be downloaded from my website:
http://www.mwebng.net/

And for the javascript classes, you can find some nice examples too free for download on my website. . . .

Now which one is remaining?
Re: Advanced Javascript Stunts by cdeveloper(m): 12:26pm On May 27, 2009
Checked out your work , great stuff you have in there, but why have you not posted it here for others to look at it. Well you seem to have forgotten that i have seven How Tos to answer here. And whether you have implemented before or not, post it right here others look at it ,that is why i am going to shear my own ideas about them. I thought you would want to critices my code that is why i posted it right here. Anyway i still will post more on these.
Saw you codes on Upload stuff, was wondering whether what you loaded in the hidden Iframe is simple html page that sends dat to the callback function or you are loading the response in the hidden iframe and then reading the content of the loaded document in the iframe. That is not the way i see such man. Stay tuned man, you will see my own implementation on this and perhaps see that there are different ways of solving problem.
Re: Advanced Javascript Stunts by Nobody: 12:29pm On May 27, 2009
i have posted them here before, they have moved on to other pages, and i have posted them in other forums too before. Thanks man. . .
Re: Advanced Javascript Stunts by Nobody: 12:33pm On May 27, 2009
Looking forward to see your implementation. Mind you, i have upgraded most of those codes you see there.

And the hidden frame in that upload, well, this upload can read callback, and can tell if the upload fails too. . . .

I did not fully document it sef, but lets see what you have. One thing in programming is that, no one is a master
of all. As you advance, you also move forward, and i dont believe i have reached my peak yet, not just yet. . .
Just starting really. . .
Re: Advanced Javascript Stunts by segsalerty(m): 12:50pm On May 27, 2009
yes, thats true
this thread is getting interesting thou
Re: Advanced Javascript Stunts by Nobody: 10:27am On May 28, 2009
cdev, i am not here to criticize. In coding, first rule is to get it to work, then improving comes after. Your codes look ok, thouh i have not really
tested them out, i am still waiting for the main ones.
Some of the stunts there are basic, some are advanced, but i have at some points used all of them and even more, after seeing u pull out
all of them, maybe i will criticize - positively, by improving on those codes.
i cannot grade your skills yet based on what you have posted so far. . .
Re: Advanced Javascript Stunts by cdeveloper(m): 2:47pm On May 28, 2009
I am not sure i can grade my own skills either,all i do is to figure how to implements stuff and i do. It is not for me to do the grading. Anyway , Today i will be talking about How to create classes in JavaScript The question is can classes be created in JavaScript? and the blunt answer is BIG NO!!! This is because JS does not have the features that full blown languages have to implement classes.However there are features in JS that developers can use to mimic classes like in other languages.
One of such feature is what is the understanding that Everything inn JS is an Object, String,Date,Function etc are pure object in JS and if the building blocks are object then we can create class like object with then, another important property of the language is what is call Closure which in its simplest definition is the definition of a function right inside another function and having access to the inner function even when the outer function has gone out of scope. I will be discussing Closures when i get to building object with private and public properties in JS.
A class is simply a blueprint from which objects can be manufactured. to build a qiuck javascript object the old fashion way ,i will do something like this:

var myObj=new Object();
//assign first property to this object
myObj.property1="Data1";

or
myObj["property1"]="Data1";

//assign property 2

myObj.property2="Data2"

etc

This is an old fashion way of building an object in JS .Imagine you are working on a large project with lots of JS files and you end up creating global variables like we have done above, you will end up overwriting the global variables that you will spend perhaps ages to debug. I do not like the sound of that. Creating object the new gives you some control and elegance if you are the type that like things to standout on their own.
this are the various way to build object in JS

1. Using the {} or curly braces symbol

var objBase={};
//define properties
objBase={
      property1:null,
      property2:"data1",
      property3:true,
  //define some methods
      initClass:function()
             {

                //TODO:
              },

      doSomething:function(param1,param2)
       {

       }
};

2. Using a base Function

  function objBase()
  {
      this.property1="data1";
      this.property2="data2";
   
  }
// add some method to this object using the prototype property

objBase.prototype.method1=function()
   {
     //TODO:
   }

objBase.prototype.method2=function()
  {
      //TODO:
   }

3. Using a base Function with the new keyword

var objBase=new Function()
   {
      //add properties
       this.property1=''data1";
       this.property2="data2";
     
     //add some methods
      this.method1=function()
      {
          //TODO:
      };
      this.method2=function(param1,param2)
     {
         //TODO:
     };
   }

I have listed three basic way of creating defining a class in JS from which objects can be created. Among these three methods i preferred option 1 because it gives me control over my object and it tends to look like or it is in fact a Singleton Pattern Implementation for there can only exactly on instance of the object at any time (t). Option 1 and to are similar because in much the same way. to use this class in any place in a page the includes the file within which you defined the class or within any function that is not defined in the class simple reference it by its name then a dot notation and then any method name or property can be accessed like this
objBase.method1(),objBase.property1; etc.

The second option works diffrently, you have to instanciate the class before you can use it like this
var obj= new objBase(); and then obj.method1();obj.method2() etc. Because option 1 is a lot easier to work with i can go elegant with it by going as far as building a namespace for myself much like the YUI library. That ensures that if i am using a third party script in my project it does not interfere with my own classes. Using option 1 i can define any length of namespaces for myself. to illustrate i am going to show how to define two JAVA classes namely[b] Date and ArrayList [/b] classes which are contained in the namespaces[b] java.util.Date and java.util.ArrayList[/b] in pure javascript

define the base class java
var java={};

//define the util namespace

java.util={};

//define the Data class

java.util.Date={};

//define the ArrayList class

java.util.ArrayList={};

this is just how to implement namespace in JavaScript, to define namespaces using option 2  we do something like this

java=function(){};
java.util=function(){};
java.util.Data=function(){};
java.util.ArrayList=function(){};

that is just it.So if you are wondering how to implement classes in JS , CLASSES CAN BE IMPLEMENTED IN JS USING THE LANGUAGE'S FEATURES THAT LENDS THEM THEMSELVES TO THE ELEMENTS OF A TYPICAL CLASS DEFINITION ANY IN LANGUAGE
Re: Advanced Javascript Stunts by Nobody: 9:44am On May 30, 2009
Yep: classes can be created using javascript:

cookie.class.js

function jcookies() {}
jcookies.prototype.online=function() {return location.href.indexOf("http"wink==-1 ? false : true;}
jcookies.prototype.set=function (cname,cvalue) {
if(this.online()) {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;path=/;";}
else {document.cookie = cname + "=" + escape(cvalue) + "; expires=Mon, 31 Dec 2099 23:59:59 UTC;";}
}
jcookies.prototype.erase=function(cname) {
if(this.online()) {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;path=/;";}
else {document.cookie = cname + "=" + "" + "; expires=Mon, 31 Dec 1899 23:59:59 UTC;";}
}
jcookies.prototype.get=function(sName) { var aCookie = document.cookie.split("; "wink;
for (var i=0; i < aCookie.length; i++) {
var aCrumb = aCookie[i].split("="wink;
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
return "";
}


cookie.class.test.html

<title>My Cookie Test</title>
<script src="cookie.class.js"></script>
<script>
var food=new jcookies();

function savex() {
food.set("meal",cook.value);
alert("Swallowed "+cook.value);
}

function loadx() {
cook.value=food.get("meal"wink;
}

function erasex() {
cook.value="";
food.erase("meal"wink;
alert("Vomited meal"wink;
}

</script>


<input type="text" id="cook">
<input type="button" value="Save" onclick="savex()">
<input type="button" value="Load" onclick="loadx()">
<input type="button" value="Vomit" onclick="erasex()">


Online demo: http://www.mwebng.net/demos/cookies/cookie.test.html
Downloadable: http://www.mwebng.net/demos/cookies.zip

That works iight?

But lemme say this one: javascript is not OOP (Object Oriented Programming) per say, but it is made
up of objects. The prototype method has its own limitations, but does have some properties of
oop such as inheritance, polymorphism. . . but not really perfect though. . .
I guess this will serve for now. . .

**************************************************************************

Just kidding, cdeveloper, i actually prefer method 2. . . .suits me fine!
Re: Advanced Javascript Stunts by Nobody: 9:48am On May 30, 2009
Lemme add that i find your knowlege about javascript outstanding, and to everyone, i agree 100% to everything dat cdeveloper said in his last post above this, except that i prefer method 2 rather than 1 !

@cdeveloper, i have a question for you, what is this method called:


msgbox.class.js
var msgbox = {
loaded:false,

init: function() {
this.onclose=null;
this.onok=null;
this.msgcount=0;
this.reference=null;
this.loaded=true;
this.dragmode=false; //drag mode
this.dragable=false; //drag flag

this.config=msg_config;

//cache images
if(msg_config.imageCache!=""wink {this.cacheImages();};

//create shadow box
var element=document.createElement('DIV')
document.body.appendChild(element);
element.id=msg_config.instanceName2;


var style2=msg_config.shadow[0];
element.style.cssText+=style2.line1;
element.style.cssText+=style2.line2;


element.id=msg_config.instanceName2;
this.shadow=document.getElementById(msg_config.instanceName2); //screen shadow

this.resize2();

//create message holder
var element=document.createElement('DIV')
document.body.appendChild(element);
element.id=msg_config.instanceName;

this.shadowbox=document.getElementById(msg_config.instanceName); //contains messagebox


//attach events for shadowbox
if(window.addEventListener){ // Mozilla, Netscape, Firefox
window.addEventListener('resize', msgbox.resize, false);
window.addEventListener('error', msgbox.error, false);
window.document.addEventListener('mousedown', msgbox.mousedown, false);
window.document.addEventListener('mouseup', msgbox.mouseup, false);
window.document.addEventListener('mousemove', msgbox.mousemove, false);
} else { // IE
window.attachEvent('onresize',msgbox.resize);
window.attachEvent('onerror',msgbox.error);
window.document.attachEvent('onmousedown',msgbox.mousedown);
window.document.attachEvent('onmouseup',msgbox.mouseup);
window.document.attachEvent('onmousemove',msgbox.mousemove);
}
},


cacheImages:function () {
var images=msg_config.images[0];
var s = msg_config.imageCache.split("|"wink;

for(var i=0;i<s.length;i++) {
key=s[i];

try {
var icon=eval("images."+key);
} catch(exception) {
var icon=null;continue;
}
icon=this.config.imagePath+icon;
var c= new Image(5,5);
c.src=icon;

}

return;
},

resize2:function() {
var scnWid,scnHei;
if (self.innerHeight) // all except Explorer
{
scnWid = self.innerWidth;
scnHei = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
// Explorer 6 Strict Mode
{
scnWid = document.documentElement.clientWidth;
scnHei = document.documentElement.clientHeight;
}
else if (document.body) // other Explorers
{
scnWid = document.body.clientWidth;
scnHei = document.body.clientHeight;
}


this.shadow.style.width=scnWid+document.body.scrollLeft;
this.shadow.style.height=scnHei+document.body.scrollTop;

return;
},

resize:function(e) {
setTimeout(function() {
msgbox.resize2();
},200);
},


ajaxRequest:function () {
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try {
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false;
},

replaceText:function(text) {
this.message=text;
this.textbox.innerHTML="<nobr>"+text+"</nobr>";
},

runEvent:function(handler) {
var e=eval("this."+handler);
if(typeof(e)=="function"wink {
var ef=e+"";i=ef.indexOf("{"wink;j=ef.lastIndexOf("}"wink;ef=ef.substring(i+1,j);
with(this) {try {eval(ef);} catch(err) {void(0);return false;}}
}
return true;
},


setText:function(text) {this.replaceText(text);},

setIcon:function(button) {
var images=msg_config.images[0];
try {
var icon=eval("images."+button);
} catch(exception) {
return false;
}
icon=msg_config.imagePath+icon;
var temp=msg_config.iconWidth;
if(temp!=""wink {temp=" width='"+temp+"' ";}
this.message="<img "+temp+" align='absmiddle' src='"+icon+"'>&nbsp;&nbsp;"+this.message;
this.replaceText(this.message);
return true;
},

setTitle:function(text) {
this.title=text;
this.titlebox.innerHTML="<nobr>"+text+"</nobr>";
},


mousedown:function(e) {
//select mode
if(!msgbox.dragmode) {msgbox.dragable=false;return;}

var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;

//bubble
if(targ.parentNode.tagName=="TD"wink {targ=targ.parentNode;}
if(targ.id!="m_titlebox"wink {return;}

//switch target
this.mbox=document.getElementById("m_mbox"wink;
targ=this.mbox;

this.dragable=true;
this.pixelLeft=targ.offsetLeft
this.pixelTop=targ.offsetTop
this.clientX=e.clientX
this.clientY=e.clientY
},

mouseup:function(e) {
this.dragable=false;
},

error:function(e) {
//alert("Error detected!"wink;
//return true;
},

mousemove:function(e) {
var targ;
if (!e) var e = window.event;

//if button is not left in IE/NE return
if((document.all&&e.button!=1)||(!document.all&&e.button!=0)||(!this.dragable)) {return;}

//move it
try {
var cLeft=this.pixelLeft+e.clientX-this.clientX;
var cTop=this.pixelTop+e.clientY-this.clientY;
this.mbox.style.left=cLeft;
this.mbox.style.top=cTop;
} catch(err) {
this.dragable=false;
void(0);
}

},

setActionText:function(text) {
this.action=text;
this.actionbtn.value=text;
},

setCloseText:function(text) {
this.close=text;
this.closebtn.value=text;
},



doModal:function() {this.shadow.style.display="block";},

loadMedia:function(filename) {
var i=filename.lastIndexOf("."wink;
var ext=filename.substr(i+1,filename.length);
switch(ext) {
case "css":
var fileref=document.createElement("link"wink
fileref.setAttribute("rel", "stylesheet"wink
fileref.setAttribute("type", "text/css"wink
fileref.setAttribute("href", filename)
break;
case "js":
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript"wink
this.fileref=fileref;
fileref.setAttribute("src", filename);
break;
default:
return
}
//complete insertion
document.getElementsByTagName("head"wink[0].appendChild(fileref);
return;
},


//load ajax
load:function() {
var jfunc="";
switch(this.load.arguments.length) {
case 1:
url=this.load.arguments[0];
break;
case 2:
url=this.load.arguments[0];
jfunc=this.load.arguments[1];
break;
default:
return false;
}

//jfunc validate start
if(jfunc!=""wink {
try {eval(jfunc);this.jfunc=null;alert("The function "+jfunc+" already exist!"wink;} catch(err) {
if(err.code!=null) {alert("The function "+jfunc+" already exist!"wink;this.jfunc=null;} else {
this.jfunc=jfunc; //save for future reference
}}}
//jfunc validate stops

if(url==""wink {return false;}
var s = url.split(","wink;

url=s[0]; //default ajax page
if(s.length>1) {
for(i=1;i<s.length;i++) {
this.loadMedia(s[i]);
}
}


var bustcacheparameter=(url.indexOf("?"wink!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
if(this.msgcount==0) {this.show(this.config.ajaxLoading,"","","title=false|action=close"wink;}
this.mygetrequest=new this.ajaxRequest()
this.mygetrequest.onreadystatechange=function(){
if (msgbox.mygetrequest.readyState==4){
if (msgbox.mygetrequest.status==200 || window.location.href.indexOf("http"wink==-1){
var data=msgbox.mygetrequest.responseText;
msgbox.replaceText(data);
msgbox.onload2();

}
else{
msgbox.replaceText(msg_config.ajaxError);
msgbox.runEvent("onfail2"wink;
}
}
}
msgbox.mygetrequest.open("POST", url+bustcacheparameter, true);
msgbox.mygetrequest.send(null);
},

jload:function(url) {
var bustcacheparameter=(url.indexOf("?"wink!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
this.mygetrequest2=new this.ajaxRequest()
this.mygetrequest2.onreadystatechange=function(){
if (msgbox.mygetrequest2.readyState==4){
if (msgbox.mygetrequest2.status==200 || window.location.href.indexOf("http"wink==-1){
var data=msgbox.mygetrequest2.responseText;
msgbox.onjload2(data);
}
else{
msgbox.runEvent("onjsfail"wink;
}
}
}
msgbox.mygetrequest2.open("POST", url+bustcacheparameter, true);
msgbox.mygetrequest2.send(null);
},

onload2:function() { //ajax load successful!
//clear out abort
this.onabort=null;
this.runEvent("onload"wink;

//check for jfunc
if(this.jfunc!=null) {
try {eval(this.jfunc);this.jfunc=null;} catch(err) {setTimeout("msgbox.loadFunc()",1000);}
}
},

onjload2:function(jscript) { //ajax load successful!
try {eval(jscript)} catch(err) {void(0);}
if(this.onjsload!=null) {setTimeout(msgbox.onjsload,1);}
},

loadFunc:function() {
try {
eval(this.jfunc);
if(this.onjsload!=null) {setTimeout(msgbox.onjsload,1);}
} catch(err) {
if(this.onjsfail!=null) {setTimeout(msgbox.onjsfail,1);}
}
this.jfunc=null;
return false;
},

onfail2:function() {

if(this.onfail!=null) {setTimeout(msgbox.onfail,1);}
},

recall:function() {
this.shadowbox.style.display="block";
},

move:function() {
switch(this.move.arguments.length) {
case 1:
this.mbox.style.left=parseInt(this.move.arguments[0])+"px";
break;
case 2:
this.mbox.style.left=parseInt(this.move.arguments[0])+"px";
this.mbox.style.top=parseInt(this.move.arguments[1])+"px";
break;
}
return;
},

show:function() {
if(!this.loaded) {this.init();}
s
//clear cache
this.message="";
this.button="";
this.title="";
this.options="";
this.action="";
this.close="";

this.callback="msgbox.hide();"; //default callback

switch(this.show.arguments.length) {
case 0:
//no parameters will recall
this.recall();
return false;
case 1: //message only
this.message=this.show.arguments[0];
this.title=msg_config.defaultTitle;
break;
case 2: //message,button only
this.message=this.show.arguments[0];
this.button=this.show.arguments[1];
this.title=msg_config.defaultTitle;
break;
case 3: //message,button,title only
this.message=this.show.arguments[0];
this.button=this.show.arguments[1];
this.title=this.show.arguments[2];
break;
case 4: //message,button,title, options
this.message=this.show.arguments[0];
this.button=this.show.arguments[1];
this.title=this.show.arguments[2];
this.options=this.show.arguments[3];
break;
case 5: //message,button,title, options,callback
this.message=this.show.arguments[0];
this.button=this.show.arguments[1];
this.title=this.show.arguments[2];
this.options=this.show.arguments[3];
this.callback=this.show.arguments[4];
break;
default:
alert("Too many parameters"wink;
return false;
}

//fetch table
element=document.getElementById(msg_config.instanceName);

var table=msg_config.table[0];
var style=msg_config.style[0];
var images=msg_config.images[0];

if(this.button!=""wink {
try {
var icon=eval("images."+this.button);
} catch(exception) {
var icon=null;
}

if(icon!=null) {
icon=msg_config.imagePath+icon;
//this.message="<table><tr><td><img width=22 align='left' src='"+icon+"'></td><td>"+this.message+"</td></tr></table>";
var temp=msg_config.iconWidth;
if(temp!=""wink {temp=" width='"+temp+"' ";}
this.message="<img "+temp+" align='absmiddle' src='"+icon+"'>&nbsp;&nbsp;"+this.message;
}
}

var source=table.line1;
source+=table.line2;
source+=table.line3;
source+=table.line4;

//optimization
var key; var val;
if(this.options!=""wink {
var s = this.options.split("|"wink;

//opti-A
for(var i=0;i<s.length;i++) {
key=s[i].split("="wink[0];
val=s[i].split("="wink[1];
switch(key) {
case "action":
this.action=val;
break;
case "close":
this.close=val;
break;
}
}
}


if(this.action==""wink {this.action=" OK ";}
if(this.close==""wink {this.close=" Cancel ";}

//substitutions
source=source.replace(/#title/,"<nobr>" + this.title + "</nobr>"wink;
source=source.replace(/#text/, "<nobr>"+this.message+"</nobr>"wink;
source=source.replace(/#action/, this.action);
source=source.replace(/#close/, this.close);

//render
element.innerHTML=source;

//fetch objects
var tab=element.getElementsByTagName("TABLE"wink;
this.mbox=tab[0];
var tds=element.getElementsByTagName("TD"wink;
var buttons=tds[2].getElementsByTagName("INPUT"wink;

//store references for future usage
this.titlebox=tds[0];
this.textbox=tds[1];
this.btnbox=tds[2];
this.actionbtn=buttons[0];
this.closebtn=buttons[1];

//create ids
this.mbox.id="m_mbox";
this.titlebox.id="m_titlebox"; this.titlebar=this.titlebox;
this.textbox.id="m_textbox";
this.btnbox.id="m_btnbox";
this.actionbtn.id="m_actionbtn";
this.closebtn.id="m_closebtn";


//apply style rules
this.mbox.style.cssText=style.cover;
this.titlebox.style.cssText=style.title;
this.textbox.style.cssText=style.text;
this.btnbox.style.cssText=style.btn;
this.actionbtn.style.cssText=style.action;
this.closebtn.style.cssText=style.close;

//attach callback functions
this.actionbtn.onclick = function() {
try {eval(msgbox.callback);} catch(exception) {void(0);}
if(msgbox.onok!=null) {setTimeout(msgbox.onok,1);}
};

this.closebtn.onclick = function() {msgbox.hide();};


//optimization

//opti-B
if(this.options!=""wink {
for(var i=0;i<s.length;i++) {
key=s[i].split("="wink[0];
val=s[i].split("="wink[1];
switch(key) {
case "type":
if(val=="OKOnly"wink {this.closebtn.style.display="none";this.btnbox.style.textAlign="center";}
else if(val=="OKCancel"wink {void(0);}
break;
}
}
}

//default button: ok
if(this.options.indexOf('type=')==-1) {this.closebtn.style.display="none";this.btnbox.style.textAlign="center";}

//optimize width
if(parseInt(tab[0].offsetWidth)<parseInt(msg_config.minWidth)) {tab[0].style.width=msg_config.minWidth+"px";};

//setup position
element=document.getElementById(msg_config.instanceName).style.display="none";
this.resize2();

this.mbox.style.cssText+=";position:absolute;";
topx=(document.body.clientHeight/2);
topx=topx-parseInt(this.mbox.clientHeight)+document.body.scrollTop;
this.mbox.style.top=topx;

leftx=(document.body.clientWidth/2);
leftx=leftx-(parseInt(this.mbox.clientWidth)/2)+(document.body.scrollLeft/2);
this.mbox.style.left=leftx;




//opti-C
//preset drag mode
this.dragmode=false;
this.titlebar.style.cursor="default";

if(this.options!=""wink {
for(var i=0;i<s.length;i++) {
key=s[i].split("="wink[0];
val=s[i].split("="wink[1];
switch(key) {
case "modal":
if(val=="true"wink {
//alert('Modal');
this.shadow.style.display="block";
}
break;
case "drag":
if(val=="true"wink {
this.dragmode=true;
this.titlebar.style.cssText+=";cursor:pointer;cursor:hand;";
}
break;
case "title":
if(val=="false"wink {this.titlebox.style.display="none";}
break;
case "buttons":
if(val=="false"wink {this.btnbox.style.display="none";}
break;
case "left":
this.mbox.style.left=val+"px";
break;
case "left":
this.mbox.style.left=val+"px";
break;
case "top":
this.mbox.style.top=val+"px";
break;
case "width":
this.mbox.style.width=val+"px";
break;
case "height":
this.mbox.style.height=val+"px";
break;
}
}
}

this.shadowbox.style.display="block";


//reference dim override
if(this.reference!=null&&this.reference.style.display!='none') {
var l=this.getElementLeftPosition(this.reference);
var t=this.getElementTopPosition(this.reference);
l += (this.reference.offsetWidth/2);
l -= (this.mbox.offsetWidth/2);

t += (this.reference.offsetHeight/2);
t -= (this.mbox.offsetHeight/2);
this.mbox.style.left=l;
this.mbox.style.top=t;
}

this.msgcount++;
},

isinView: function (oObject) {
var oParent = oObject.offsetParent;
var iOffsetTop = oObject.offsetTop;
var iClientHeight = oParent.clientHeight;
if (iOffsetTop > iClientHeight) {return true;} else{return false;}
},

abort: function() {
this.mygetrequest.abort();
this.onclose=null; //override
this.hide();
//alert("Connection aborted, "wink;
this.runEvent("onabort"wink;
},

getElementLeftPosition: function(e){
var x=0;
while(e){
x+=e.offsetLeft+e.clientLeft;
e=e.offsetParent;
}
return x;
},

getElementTopPosition: function(e){
var y=0;
while(e){
y+=e.offsetTop+e.clientTop;
e=e.offsetParent;
}
return y;
},


hide: function() {
this.shadow.style.display="none";
this.shadowbox.style.display="none";
this.runEvent("onclose"wink;
}
}
msgbox.init();
Re: Advanced Javascript Stunts by segsalerty(m): 9:56am On May 30, 2009
whats all these?
i am running away from this thread ooo , not meant for a baby programmer like me ,
i leave the room for the Gurus !
bye bye
Re: Advanced Javascript Stunts by Nobody: 10:02am On May 30, 2009
Hey nobody should run away, i am still tryin to access javascript's skills here. . .and i can bet he can read what i have just posted,
it is a javascript object, the main engine behind the message box class that is free for download on the dhtml area of my website. . .
The outdated message box that is. . .
Re: Advanced Javascript Stunts by segsalerty(m): 10:20am On May 30, 2009
ok sir !
i will wait and see , Thats why i wrote this code
<script type="text/javascript">
<!--
var dhtml_codes;
var cdeveloper;
function Segsalerty(){
if(isNotReadable(dhtml_codes)){
return true
}
elseif(shouldBeAbleToRead(cdeveloper) != true ){
return alert("Thats too Bad! and This function is disappointed  "wink;
}
else{
return alert("Good Job ! and This function is Impressed  grin"wink;
}
}
-->
</script>
Re: Advanced Javascript Stunts by cdeveloper(m): 11:33am On Jun 01, 2009
That was quite a lengthy code you have in there, if you ask me what method you are using i tell you what, just like they say that all roads lead to Rome, so i tell you that JavaScript is a mythical dynamic language that you can bend anyhow you want to achieve your goal. You are mixing alot in there. You have a mixture of Option 1 and Option 2 in you code and i see Global variables here and there.  Thanks for the lengthy code man , i would appreciate if you have the understand that we are here to share what we know will help others in there work and not to test other's skill or understanding of JS. If i where to do that then the aim of having a general forum is defeated.

Today i will be looking at Creating Private Properties and Methods in Javascript
Just like in the mature languages we have the concept of private, protected,public,final,abstract properties so also we can implement some of these concept in JS too. The dynamism of JS gives us the power to mimic this concept and implement it in JavaScript. The implementation of Private and public properties and method in JS is brought to you through a concept known as Closure I recalled i hinted on this when i was talking about implementation of classes in JS. so i will look in to that further here.To start with what do you guys think will happen when this function is ran

function genericFacotry()
{
    var timestamp=new Date().getTime();

    return function()
                           {
                             return timestamp;
                           }

}

If i run the function above say

var instance=genericFactory();

What do you guys think instance will hold, a function or a timestamp variable? Well if you guess right it will hold a reference to the inner function and when i do something like this alert(instance()) you are going to see the timestamp we defined inside the function genericFactory(); this may look too simple but the magic start happening when you look back at how JavaScript work. JavaScript is an Interpreted language meaning that as soon as the functions are encountered, the are executed immediately and there after, the go out of scope; but here strange things are happening. I defined a function genericFactory() and after i ran it it was suppose to go out of scope , and the variable timestamp that i defined right within the context of that function is still accessible even after the function genericFactory() has gone out of scope.This is what is called Closure, the ability to define a function within the context of another function and have the defined function have access the to variables defined within the context of the containing function . This idea forms the building block of Creating Private and Public properties in JavaScript By Private properties i mean those properties that are only accessible within the context of the containing function and by public properties i mean those ones that can be accessed public or have a public interface. To illustrate what i mean consider the code below

function saveName(n)
{
   var name2Uppercase=n.toUpperCase();
   var nameLength=n.length;
   
   return {
                 capitalize:function(){return name2Uppercase;},   
                 size:function(){nameLength;}
              };
}

  var nameObj=saveName("javascript is a voodoo language"wink;
 
   alert(nameObj.capitalize());

you will get the capitalized sentence"JAVASCRIPT IS A VOODOO LANGUAGE";
and if you do something like alert(nameObj.size())
it will return the number of characters in the sentence, which is 31 characters

This may look rather simple but the point i intend making is that ,the variables nameLength and name2Uppercase are private properties that can not be accessed outside the context of the function saveName() but can be accessed within the public interfaces capitalize() and size() defined within the function. This is how private and public properties can be implimented in JS. To illustrate with concreate example consider this

var Person=function()
{
   var name="cdeveloper";
   var name2Uppercase=null;
    function toUpper()
    {
       name2Uppercase=name.toUpperCase();
    }
    return{
               getName:function()
                            {
                              return name;
                            },
                setName:function(newName)
                            {
                               name=newName
                            },
                getSize:function()
                            {
                               return name.length;
                            }
              };
}();

Now look at what is happening

alert(Person.name) returns undefined;
alert(Person.getName()) return  cdeveloper;
alert(Person.getSize())  returns 10

Person.setName("Ama"wink;

alert(Person.getName())  returns Ama;
alert(Person.getSize())  returns 3

This is  how to implement Private properties and methods in JavaScript, if you look closely you will see the parenthesis added at the end of the function defination, this is called anonymous function that runs immediately the page containing this script is run. it instantly create the Person object and i can access its properties anytime
Re: Advanced Javascript Stunts by segsalerty(m): 8:14pm On Jun 01, 2009
am disappointed !
@cdeveloper !
Its really cool what DHTML did by calling the[b] function javascriptSkill_fetch_cdeveloper(){}[/b] grin , we are not fools NL , look at other forums , not a simpe task for someone to just come up with tutotial thread without being extra ordinary good! coz we know where to get Ebooks / tutorials for free and we dont care about who wrote them or who invented the knowledge ,
so, coming here to shine star from what you sourced elsewhere will deffinately return false; tongue,
so, abeg !
you know what to do ! i wont tell ya !
Re: Advanced Javascript Stunts by Nobody: 10:43am On Jun 02, 2009
Ehm, @cdeveloper, when i first came to this forum, i started out really advanced, and lots of ppl were complaining that
my codes were rather too advanced for them to follow, so i need to just slow it down and write simpler codes so they can follow.

This your last post, i can bet the folks that need to learn javascript cannot quite follow, and those are the people that need to learn.

Meanwhile, you answered my last question well (and sorry for the code being so lengthy), so i have upgraded your ranking. . .

A little insight there is that, that method i used has private and public properties too, it works like a class except that, you cannot create
new instances. . . and that will be all for today, have a nice day!
Re: Advanced Javascript Stunts by cdeveloper(m): 1:24pm On Jun 02, 2009
It was never my object to get someone disappointed with my last post. What i did in there was to create an instance object Person so that i can illustrate the point i was trying to make. If i got you guys lost in that last post then i guess i have to digress a little and talk about Anonymous Functions ,perhaps it could help clarify alot of what is going on in that post.

An Anonymous function is a function that is nameless and runs instantly the page containing it is fully loaded on the Browser.
To define an anonymous function you simply do something like this

(function(){//code goes in here})();

So if i want to create a function that i want to execute immediately a page containing it is loaded i could do something like this

(function(){
     
   for(i=0;i<20;i++ )
   { alert(i);}
})();

if this code in included in a page and that page is loaded in a browser before the page finishes loading the function will be executed. You do not need to call it for it to be executed at all .What is happening here is that  when the JS Engine encounters the parenthesis surrounding the function it immediately executes its content which is a function without name. However if you do not want the function to go out of scope after executing, you can assign it to a variable for later reference. That is what i did in the Person Object that i used in my previous post. 

Please note that you can pass a variable to this function by specifying then in the outer parenthesis i.e

(function(){})(var1,var2,var3,, );

To make use of this variable within the function you have to pick them up as you specified then i.e

( function(v1,v2,v3,, ){// the code goes in here } )(var1,var2,var3);

You guys may not see the use of using this thing called anonymous function but if you have worked with JS Libraries like YUI from yahoo, and you need to use say the Dom component of the library you will have to type something like this YAHOO.Util.something.something.Dom;

That is how they chose to develop there own name space, to have just one global Namespace called YAHOO and have every other component build from there.

If you are developing you own object that uses the YUI Library, you certainly get tired of typing those lengthy Namespace stuff, this is where the anonymous function comes in to play suppose that Person object i used for ilustration above uses the Yahoo Library objects Dom, i would save myself the lengthy typing by doing something like this using an anonymous function

var Person=(function(dom){
    //The parameter dom is a reference to the YAHOO.Util.Dom object
    // between dom and YAHOO.Util.Dom which will you prefer to use? well for me the shorter dom is ok for me

})(YAHOO.Util.Dom);

When the JS engine encounters this code it will immediately execute it and assign the output of the execution to a variable called Person,so with this variable at my disposal i can further call its public interfaces or methods that where created when the code is executed.

This is to those who feel that the ideas in here are  rather  difficult. The Beginning title of this Post is Advanced JavaScript Stunts. I stated upfront what will be coming from the beginning.So if somehow it is not getting any more interesting then it is time for you not to exit this Forum but to become more practical. Copy the codes, create a simple index.html on your system, run the code and see things for you self, break ,tweek and alter the code. That way you beginning to put your mind to learning. For they say that the best way to learn programming is through enduring practice and determination. I must confess, there are still stuff that i myself do not even understand in JS. IsStudied JS from the JS codes powering wikipedia site. Yes! i printed out the entire code and studied it as you would study a course in school and till today i still have those printouts with me for reference purpose. when you interact with the Masters like those working for Mozilla Project or study their articles you tend to become like them.Have you ever wondered what is powering the Firefox Web Browser,well i have until i looked under the hood. it is Pure JS,XML, better known as XUL ,google for this for see what it would turn up for you

I am writing this not to discourage those who would want to learn JS but to give then the impetus. You will need the knowledge someday in you project. I will save the next How To Article    for another day.
Re: Advanced Javascript Stunts by Nobody: 5:28pm On Jun 02, 2009
Now that is very much better. And also, it is not safe that you should assume that those that call themselves veterans too can follow your
codes [for all you know many of them download scripts and stuffs without knowing how to write a single line of code].
There is no harm in downloading codes, but i alwayz stress that you should be able to do your slight modifications when necessary, which
is only possible if you know the language used to write the code to a fair extent.
Re: Advanced Javascript Stunts by Nmeri17: 1:34pm On Mar 11, 2016
heeeeh.. where is this OP o sad

(1) (Reply)

Joomla 1.7 Is Out / Features On Anti Bribery Website / Gossip Blogger "Yomi Adegboye" Personal Website Hacked

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 144
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.