Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / NewStats: 3,178,848 members, 7,906,119 topics. Date: Wednesday, 31 July 2024 at 05:25 AM |
Nairaland Forum / Science/Technology / Webmasters / Advanced Javascript Stunts (1178 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)
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("&" url=url+"&callback=processResponse"; } var script=document.createElement("script" script.type='text/javascript'; script.src=url; document.getElementsByTagName("head"[0].appendChild(script); } function processResponse(data) { if(data.name){alert("the server returned "+data.name+""} } </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" $jsonData=json_encode($data); echo $callback."(".jsonData.""; 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() {} cookie.class.test.html
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 = { |
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 " } else{ return alert("Good Job ! and This function is Impressed " } } --> </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" 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" 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] , 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; , 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 |
(1) (Reply)
Anonymous Hackers Go After Sony, Make It Personal: Very Personal / Having Problems Sending Bulk Sms To Mtn Numbers? / FOR IMMEDIATE REMOVAL
(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. 136 |