PDA

View Full Version : Amazing Functions in JavaScript



magicyte
07-31-2008, 04:57 PM
Here is one amazing function that is a use in JavaScript that one may LOVE to use instead of document.getElementById():


<!-- Makes coding SO much easier -->
function getObj(obj)
{
if(document.all) return document.all[obj];
else if(document.layers) return document.layers[obj];
}

I may have accidently reused it, but I have some others that you guys might like:


<!-- These are plain stealing and calling them your own, however it is convenient in writing shorter code -->
function random()
{
return Math.random();
}

function acos(int)
{
return Math.acos(int);
}


<!-- Love these -->
function setVal(obj,str)
{
getObj(obj).value = str;
}

function setHtml(obj,str)
{
getObj(obj).innerHTML = str;
}

See what functions can do for you? Feel free to take these and make them your own. Change 'em up too!

-magicyte

jscheuer1
07-31-2008, 06:09 PM
Here is one amazing function that is a use in JavaScript that one may LOVE to use instead of document.getElementById():

I can't see why, neither of those two methods are required in version 5+ browsers. No current browser uses document.layers, and if you were to have some antique around that did, it should be the first test, not the second as you have it there - to avoid possible errors.

Seems like a bit of extra typing at first to save little, combined with having to memorize the other way to do things. In the case of the first one, it will fail to retrieve the element in many cases due to its lack of support for document.getElementById(). And it really isn't getting an object (when it works at all) as its name implies unless that object happens to be an element.

Functions are great if they work, but generally more than a few lines are required to deliver much utility.

magicyte
08-05-2008, 09:55 PM
I am sorry if what I posted isn't useful for those of you with IE 5+ (I have IE 4 w/ WINDOWS XP). I just posted it because I find it easier to use than document.getElementById(), considering I use it a lot.

You are right. getObj doesn't get an object. But, man oh man, I wish that JavaScript was compiled so that everything could be compatible with other browser applications.

-magicyte

mburt
08-05-2008, 09:59 PM
I find it easier to use than document.getElementById(), considering I use it a lot.

I just define this at the beginning of my file:


var $ = function(e) {return document.getElementById(e);};

Simple.

magicyte
08-05-2008, 10:11 PM
Does it involve PHP? I noticed you used $...

-magicyte

codeexploiter
08-06-2008, 02:55 AM
Does it involve PHP? I noticed you used $...

-magicyte

You can declare a variable in JS whose name is $ need not be in PHP :)

jscheuer1
08-06-2008, 03:15 AM
I have IE 4 w/ WINDOWS XP

Um, Windows XP came with IE 6 I think, at least 5 or 5.5, what happened? Most pages on the web won't render well, if at all in IE 4, and most scripts will either not work, or will degrade to a very simplistic level. IE 4 will often report script errors on pages that technically have none. Many commercial sites require at least IE 5.5 if you are using IE. How on earth do you get by with such a relic?

Twey
08-06-2008, 04:06 AM
I just posted it because I find it easier to use than document.getElementById(), considering I use it a lot.You shouldn't. Both the methods it is capable of using to look up an element are deprecated. You should use document.getElementById(). You may assign a reference with a shorter name if you like. However, that name should not be $.
You can declare a variable in JS whose name is $ need not be in PHPYou can, but should not. Use of the $ character in identifiers is reserved for machine-generated code (ECMA-262 section 7.6).

My own favourite utility functions are:
function map(f, a) {
for (var i = a.length - 1, r = []; i >= 0; --i)
r[i] = f(a[i], i);

return r;
}

function filter(f, a) {
if (typeof f === "string")
f = (function(f) {
return function(a) {
return !!a[f];
};
})(f);

for (var i = 0, r; i < a.length; ++i)
if (f(a[i]))
r.push(a[i]);

return r;
}

function reduce(f, a, t) {
if (!a.length)
return t;

t = t || a[0];

for (var i = 0, n = a.length; i < n; ++i)
t = f(t, a[i]);

return t;
}

function compose(f1, f2) {
return function() {
return f1(f2.apply(this, Array.prototype.slice.call(arguments)));
};
}

function bind(obj, fun, args) {
return function() {
if (obj === true)
obj = this;

var f = typeof fun === "string" ? obj[fun] : fun;

return f.apply(obj, Array.prototype.slice.call(args || [])
.concat(Array.prototype.slice.call(arguments)));
};
}... as well as a bunch of curryable operator functions. I have a few more, nicely modularised, but they're all on my desktop, which is currently kaput. If I found myself using many of these, I suspect I would switch over to the Functional Javascript (http://osteele.com/sources/javascript/functional/) library.

clueful
08-06-2008, 12:43 PM
<!-- Makes coding SO much easier -->
function getObj(obj)
{
if(document.all) return document.all[obj];
else if(document.layers) return document.layers[obj];
}Have you ever used anything but I.E.? The above function would return undefined in Mozilla and others.



function random()
{
return Math.random();
}

function acos(int)
{
return Math.acos(int);
}These are pointless and only de-objectify an object orientated language.



<!-- Love these -->
function setVal(obj,str)
{
getObj(obj).value = str;
}

function setHtml(obj,str)
{
getObj(obj).innerHTML = str;
}

See what functions can do for you?Absolutely nothing; The phrase "ashtray on a motorbike" comes to mind.

mburt
08-06-2008, 12:49 PM
You can, but should not. Use of the $ character in identifiers is reserved for machine-generated code (ECMA-262 section 7.6).

Okay, that's fair. But can you show me an example of the machine-generated reserved code?

Twey
08-06-2008, 09:42 PM
An ideal example would be Ruby on Rails, which uses an IDL on the server-side which compiles to Javascript. Ironically, this framework often uses Prototype, which uses and requires the use of various functions named '$', '$F', '$H', &c. Other candidates include the Google Web Toolkit (GWT), a Java-to-Javascript toolkit and compiler, and the Javascript backend for Yhc, a Haskell compiler.

jscheuer1
08-07-2008, 02:13 AM
An ideal example would be Ruby on Rails, which uses an IDL on the server-side which compiles to Javascript. Ironically, this framework often uses Prototype, which uses and requires the use of various functions named '$', '$F', '$H', &c. Other candidates include the Google Web Toolkit (GWT), a Java-to-Javascript toolkit and compiler, and the Javascript backend for Yhc, a Haskell compiler.

I don't think that really explains the ECMA-262 'rule', unless I missed something, it merely demonstrates how once one script uses $ (and if precautions aren't taken), it becomes a conflict if another one does so as well.

Regardless of whether or not I'm missing the boat on this one, short variable names in the global scope always present a huge potential for conflicts.

Twey
08-07-2008, 11:46 AM
You're missing the boat (nice expression) :) I'm not sure quite where our wires crossed, but that's not what I was saying at all.

jscheuer1
08-07-2008, 03:15 PM
OK, then let's get me on that boat. I could have been clearer though. What I meant to say is that your example seems more of a case of the $ (and by extension, any single character) as a global variable name being risky in any situation, than one of demonstrating the rule you cited.

And, if I am still off, where is the "machine-generated code" in your example? It appears to me to be script generated. Perhaps this is just a matter of semantics (what we are calling the code made by Ruby on Rails) here.

I guess just making it on the server side makes it "machine-generated", if that's what you mean. However, since it uses the prototype library to do that (introduce $ as a global), it is script generated in my book - made by the script that was made a part of the document's resources by the server side code. I mean if that qualifies as machine generated, so should this:


document.write('<script type="text/javascript">var $ = 'blah';<\/script>');

Twey
08-08-2008, 05:36 AM
It doesn't use Prototype in order to generate the code. The Javascript is generated by the Ruby library. prototype.js is often used in the final code.

As for your example, that code is not generated — it was written by you before the script runs. By 'machine-generated' we mean code that was authored by other code — relevantly, but not limited to, code that needs to generate arbitrary identifiers.

If you still have trouble, I suggest becoming familiar with one of the platforms I mentioned above. It's easy to see how they do things.

jscheuer1
08-08-2008, 06:21 AM
I think I am getting the hang of it. I still think my document.write qualifies. The result of that would be code written by other code. Does it make a difference who wrote the code that writes the code, how complex that code that writes the other code is, or what language it's in? Reminds me of a song lyric, "I write the songs. I write the songs."

Twey
08-08-2008, 06:19 PM
Well yes — it doesn't generate any identifiers. Using $ variables there would be a complete waste, since you know before run-time what variables it's going to create and can avoid conflicts yourself.

I think you may be missing the point a little still...

mburt
08-08-2008, 06:38 PM
I just thought using $ would be a nice way not to define any other variables I might have (like the alphabet/numerical). However I didn't know it was a reserved variable.

Twey
08-08-2008, 06:45 PM
You can call it _ if you want. By convention, names starting with '_' are do-not-touch properties, but I guess that could apply here, and at least it's not reserved in the standard. It's not a very informative name, though.

mburt
08-08-2008, 06:47 PM
It's not a very informative name, though.
True, but I hate writing out long variable names. So that's why one-character variables are simple for me. I'll use '_' from now on.

jscheuer1
08-08-2008, 11:34 PM
To me, this all seems like a nerd's pissing contest (this discussion in general, but more specifically - when $ may be used). I looked up the 262 7.6 rule and found (unofficial I admit):


This standard specifies one departure from the grammar given in the Unicode standard: The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.

Emphasis added. Either that's extremely polite language, or it means that one can use $ at one's own risk. Regardless of who/what generates what, I still think this is more of an issue about the wisdom (really the lack thereof) of using 1 char global vars.

Further, it has been increasingly my stance (and I think you are well aware of this, Twey) for quite some time now that in any well written code intended for public distribution, that global exposure should be as minimal as possible.

But if you are just coding for your site, your own amusement/learning, your own paid project over which you have full code control - in these situations, and perhaps a few others - you can do whatever you know that the code will bear. However, it may come back to haunt you.

kuau
08-12-2008, 11:22 AM
Dear Magicyte:

I just wanted to thank you for your generous offer to share your functions. Even if there are perhaps better ways, I applaud your enthusiasm and desire to give. These guys can sometimes come across a bit harsh when they are really just trying to instruct and share as well. It takes a bit of getting used to. Don't let them scare you off. :)