If you are using Rhino, to compile a JavaScript file into java byte code invoke the following class

org.mozilla.javascript.tools.jsc.Main

In most of the time, if we want to compile the JavaScript file, we should start a Rhino session in order to invoke the org.mozilla.javascript.tools.jsc.Main class. This may be trivial if we have to compile a batch of files at a time. Thus, it's better if we can have a command instead of invoking a jar class file. To see how this can be done, please go to Compilation of Javascript File

An object including a few helpful functions for debugging. Functions displaying popups or alerts are limited to a certain number of consecutive times before asking to continue, in case they end up being called in an endless loop or something.

Essentially, lets your users click a whole line of checkboxes by clicking the first and dragging down the line.

This is a crop-in script. That is to say, include it on your page, and you need do nothing else. Even primitive event handlers (element.onchange, for example) are supported, with no action on your part.

Essentially, lets your users click a whole line of checkboxes by clicking the first and dragging down the line.

This is a crop-in script. That is to say, include it on your page, and you need do nothing else. Even primitive event handlers (element.onchange, for example) are supported, with no action on your part.

Ok, so I was getting frustrated with the inability to hide data in javascript, as well as a number of other concerns with existing class structures (the requirement to use this.constructor in lieu of self, for example).

As a result, I've thrown together a nice little class constructor that accepts a class definition, as well as a class extender that allows you to build a new class from an existing one, with full access to all that private stuff.

This is a version of my previous entrant, Promise, that will work with prototype, but does not require it. It's slightly more advanced, using .apply here and there.

It's basically a function to allow any other function to poll. Polling is generally regarded as bad practice in object oriented code, but can make very simple the matter of, for example, running a bit of code only after a single-run event (like onload) occurs (whether that be in the future or past), another unrelated bit of code needs to be hack-tracked, or any other generic condition.

Note that when the function runs, it doesn't necessarily run within the scope that's called it. Its context is set to itself, rather than its normal context, and it's asynchronous, so you'll not get a return value. If you use Prototype, you can bind the function and it'll behave as it should in terms of context, but I'm unaware of a way to cause an asynch function to block execution - and you'd really rather that not happen anyway, trust me.

A wrapper on top of createElement for getting around IE problems with manipulating the name attribute. Unlike most solutions for this, it tests for which method to use once when the page loads rather than every time an element is created. By Chaos of Lost Souls MUD (a text-based fantasy RPG).

A simple, flexible formula for generating diminishing returns out of input numbers. Full explanation and home, with sample calculators and versions of the code in other languages, on the Lost Souls MUD Grimoire.

Prototype.Promise(condition, action, interval)condition is a string that you want met before an action is run.action is a function that does the action.interval is the polling rate for condition in seconds, and defaults to 1

So, for example, you may want function foo to run, but only once bar has been set:

Then, in some point in the mysterious future, thingy.retVal gets set to 5, at which point, the Promise goes into effect, and thingy.retVal becomes 10.

Where I find this particularly useful is in making sure that a document is loaded before doing something (condition="$$('body').length>=1), as you can see it used for the include functions.

Speaking of which, the following include functions are great for getting scripts and stylesheets into your page. I won't bother with examples, as they're pretty straightforward.

Meanwhile, Prototype.scriptPath will point to wherever in your server's heirarchy Prototype was loaded from. The regex, you'll note allows for names like prototype.compressed.js, prototype.modified.js, 2007-09-28.prototype.js, etc - just in case you want to keep track of your various hacks of Prototype, as I do.

This is the final version of my Javascript serializer targetted at PHP.

The point:

Objects are most easily passed over the network as serialized strings. Between serialization and unserialization, serialization is by far the easier of the two. Since object passing can sometimes be a process-hungry thing, we want to do things as quickly as possible.

My solution is to always do the hard part in compiled code, while doing the easy part in script. That is, whichever way you're passing an Object, you want to pass it in a natively decoded format for the target.

Since I work mostly in PHP, this meant writing a module that would be able to generate a string that can be decoded with PHP's unserialize() function into a PHP Associative Array (or other applicable type).

Notes:

This lib REQUIRES the Prototype lib. You can hack prototype out of it, of course (by replacing the references to Object.extend() with explicit assignments), but I can't imagine why you'd want to bother; it's used mostly with Ajax.Request anyway.

Previous versions of this code would add the .toPHP() member to the Object prototype. After trying to enumerate things, I found that this is a REALLY bad thing to do, as toPHP springs up where it's not wanted in ALL objects. As a result, I've opted to go the Prototype route and apply it as a member of the Object object.

Please note that if you pass a serialized string to PHP via GET or POST, you'll need to stripslashes() before unserialization.

This script performs reliable, cross-browser input autofocus that often can be used simply by dropping it in, with no modifications to the form or HTML body. It refuses to switch focus if it detects that the user has interacted with the form (avoiding a major source of annoyance with autofocus scripts) and correctly handles Firefox tabs opened "in the background", which most autofocus scripts fail on. Official home is on the Lost Souls MUD Grimoire.

This is a quick set of overrides for Javascript so that any variable can be passed to PHP in a GET/POST activity. Just call myVar.toPHP();

I use this little set of functions extensively in a little Javascript/PHP RPC handler I wrote. I don't have the reverse function, as I pass JSON back to the browser for the return value.

Note: This lib is not safe for binaries or HTML Elements. The former will come out similar to FTP ASCII breaks, and the latter will cause infinite recursion. If you want to make a speical case for HTML Elements, do so; you could probably just test for parentNode and create a 'safe' object from that. I didn't need it, so I didn't code it.

As for binary safety, at some point between toPHP/escape/post/urldecode/unserialize, the object breaks. Rather than create a huge fix for something I didn't need to do, I put in a quick match/hack. Don't like it? Write the fix yourself.

This is a function I created to ease headaches caused by creating and inserting new stuff in an HTML document dynamically. Essentially, it allows you to specify an HTML tag, in its entirety (attributes, styles, event handling, etc), via a single command. You can nest it, so as to create an entire element tree programmatically in a lot less time as with document.createElement.

String type: type of element to create; same information as the argument of document.createElementmixed Object attributes: attributes you want the new element to have (ie: href, src)mixed Object styles: styles for the new element (ie: width, borderLeft)(function|function Array) Object events: event handlers for the new elementHTMLElement|HTMLElement Array children: elements you want to be in the new element (ie: nesting is possible)HTMLElement parent: parent node of objectHTMLDocument document: document to create element in

It's been refactored so that:* can pass generateColourPalette an arbitrary array of colour codes and it'll generate a palette. * it hooks into the page through the external file* uses an internal stylesheet instead of inline styles

You can search for "@" or something like mail information in your page source code. You'll find nothing.You can have link of your mail with a title or just you mail address as the title. Hope this code have no problem...

libNog is a 9k library to provide somewhat easier browser-independence. It is not yet complete, and will be continuously revised. It grew from this snippet, and is still growing as I find things I use often.Presently, libNog features:

A way to browser-independently get an XMLHttpRequest object.A set of simple methods for GET, POST, HEAD, and to include other Scripts.Simple methods for className controlA completely abstracted form of getElement*Browser-independent methods for attaching and detaching event handlersAn event-normalization routineA simple one-command 'Stop the Event' routineAnd the big one: A simplified Class object by which classes can be built in JavaScript.

The above link will point you to the API documentation and history of libNog, as well as where to download the library.
]]>
Get DOM-Objecthttp://www.bytemycode.com/snippets/snippet/629/
http://www.bytemycode.com/snippets/snippet/629/comments/Wed, 07 Mar 2007 15:48:53 +0000stalkerXDOM, Element, JavaScripthttp://www.bytemycode.com/snippets/snippet/629/
Wed. Mar. 7th, 2007 3:48 PM 1stalkerXDOM | Element | JavaScript0 comments 7

Just a small snippet I discovered when I was tired writing somearrayname\[i\] I thought there was something like foreach in javascript but couldn't find any so why not make one?For those foreach(){...} lovers.

There seems to be so many hide/show scripts out there, so here's the functions I wrote and use on a regular basis - there are 7 functions, hide, show and toggle by id or class - and the getElementByClass function that does not exist as a built in Javascript function...

This is in response to the flurry of visibility scripts that just don't have all the pieces needed to make them totally useful.

I had searched high and low for a way to generate a palette of web-safe colors. Despite Google's best efforts, what I had found was lacking for my needs. So, I decided to write a library that would generate all 216 web safe colors, and then allow me to manipulate those colors in any way that I chose.

If anybody is curious as to why I would want to do something so... simple, it is because I needed a very light-weight color picker, and didn't want to mess with any fancy options.

Flexible sorting algorithm based on Quicksort with extra functionality, such as:- Direction (ie: ascending or descending)- Sort-by-path (eg: item.name, item.name.firstName or item[5])- Sorting function (returns true if two items are already sorted)- Type checking- All constants and support functions are members of the Sort() function- Testsuite with hooks for cscript and in-browser javascript, so you can tweak and optimize, and make sure it still works- Environment agnostic (can use with, say, SpiderMonkey or .Net's jsc)

This is a PHP and JavaScript Image gallery that I created. There are 2 uses for this. 1.) You can save it as index.php and place in a folder containing images and it will display the images in that folder. Example: place index.php in images/folderhttp://yoursite.com/images/folder/ This will display all images in that folder

2.) Pass in the path to the folder to display in the urlExample:Save as imagegallery.phphttp://yoursite.com/imagegallery.php?path=images/folde

This snippet allows an aspx page (c#) to accept URL parameters to allow styles or script to be dynamically appended to the rendered page.

I wrote this simple snippet to allow one of our vendors to accept a style override so that their application would morph into something more closely resembling our own portal application. Please see screenshots for clarification.

I found this to be a neat little trick for hiding(somewhat) source javacscript code from peering eyes...

This function will unload all linked javascript files so that when you view source - you see no javascript files! (Especially helpful when using FF and using web-developer tools - no linked js files are displayed) The files remain resident in memory - allowing for the functions to work.

This is a brief revision to my previous snippet. It is still what it was: a small, simple system for using XMLHttpRequest without using globals.

I'll put the API spec in the code this time, so as not to clutter the front page further.

Changes:

Changed name to HTTPRequest (far more accurate)Added HEAD requestsShortened code by making a GenericRequest functionUsed a better method for getting an XMLHttpRequest object (checks multiple MS versions and implements the latest one)

This is a simple script to provide basic cross-platform XML request functionality in Javascript. It's meant to be the core component in any AJAX style framework. It is not an instantiable object, but instead is a namespaced microlibrary.

Calling is easy:XMLRequest.GET(uri, query, callback, fallback)uri: The location you're afterquery: an associative array of form data to provide via the URLcallback: callback function of the form myCallbackFunction(objXMLHttpRequest), which is called upon successful (response = 200 OK) retrieval of the XML datafallback: myFallbackFunction(objXMLHttpRequest), which is called upon failed (response != 200 OK) retrieval of the XML data.

XMLRequest.POST(uri, query, form, callback, fallback)Similar, but does the query using the POST method. 'query' is the URL-appended data, still in associative array form, and 'form' is the same for the POST data.

This code is used in an Educational Portal product but can be tweaked to fit your need.

This code adds a small icon next to the title of a 'portlet' that resides on the page. By clicking the portlet title, the portlet usually maximizes within the constraint of the portal template - but the extra icon allows for the portlet to be opened in it's own window.

I found this to be a neat little trick for hiding(somewhat) source javacscript code from peering eyes...

This function will unload all linked javascript files so that when you view source - you see no javascript files! (Especially helpful when using FF and using web-developer tools - no linked js files are displayed) The files remain resident in memory - allowing for the functions to work.

Allows you to hide all elements on an HTML page by their tag name. Extremely handy in getting around the "Windowless Elements" problem in IE, which is a bug that puts certain elements, most commonly select boxes, on top of any other element, no matter what. As you can imagine, this causes real problems with DHTML drop-down menus and such like. This is the simplest and quickest fix I've come up with, I simply set this function to run alongside the drop-down and all of the select tags vanish before a menu drops, then I run the show function when the menu retracts.

This snippet also you to limit the input in a form field to a specified number of characters. It displays a counter so users can see how many characters they have left, and once they reach the limit the field just trims the length to your limit.

The following is a snippet from what I used when I implemented a tagboard to my site. Further revisions could/should read the LIMIT from the maxlength attribute

One way to group elements in HTML is to assign them a name attribute. Multiple elements can share a name, then you can easily access them as an array using the getElementsByName() method.

The problem is that some DOM parsers aren't keen on, or are ignorant to, this use of the name attribute, so a simple object.name returns undefined. In my case, it was a DIV in Firefox 1.5 that was behaving this way.

There is a simple work around for this that works in Firefox, I haven't tested it in others. It is to use the getAttribute method that is an extension of any element object.

This ability can be useful if you have a function that performs a transformation on the active element, and another transformation on closely related elements.

Basically, you can dynamically ask the webpage to look at a current object's attributes/values or even change the object's attributes/values. As such, running this script on any browser of your choice should show what attributes your particular browser will allow for an object reference you typed in.

This is a swear filter script I wrote for my xanga blog. I don't know if it has any application anywhere else. This will replace the swear words listed in the array with the character defined in blank_char. This isn't perfect but it works pretty well.

This is an analog clock script designed to jump in place of a div element of class 'analogclock'.

The div tag is not replaced in this custom element, but instead is used as a pseudo-document to hold the clock itself. The 'hands' are implemented using arrays of generated divs.

I was actually inspired to write this widget because of an article on About.com's Javascript pages written by a guy named Stephen Chapman. His code was a mess, but I only discovered this after delving through two layers of 'unescape()' obfuscation.

The basics: You control the look of the numbers and the 'box' model of the clock using basic CSS. You control the clock's size (it will always be square) using the 'size' attribute.

The 'seconds', 'minutes', and 'hours' attributes are for the color of the 'hand's. 'numstyle' can be 1, i, I, or '.', each refering to a different type of face-numbering for the clock

The 'localzone' attribute tells the script to use the user's local time zone. If it's '0', 'false' or 'no', the clock will use the 'clockzone' attribute to determine what time it is (the clock zone is relative to GMT, so, for example, US Eastern is -5. The clock automagically figures out if we're in DST, so you don't have to.)

The 'city' and 'country' are for if you want to put in the city/country of origin for your clock. To be honest, you can put anything there.

Lastly, I designed my version of the clock to be able to not 'tick', i.e., work like the old-school analog clocks. If you want ticking, add 'tick=1' to the attribute list

As with all of my widgets, the idea here is that you can just include the .js file and start dropping in tags without needing to know any ECMAScript at all.

Additionally, for you ECMAScripters, I was very careful to keep my pollution of the global namespace to one class: analogClock.

The basic framework of an Ajax-enabled web page. The following JavaScript shows how to send a request for an XML file and how to receive that request. Of course, in a real life scenario, you'll have to implement better error trapping and actually do something with the XML that gets returned.

I use this in my AJAX as a quick way to get the Value of the selected item in a Select HTML object. If nothing is selected, it returns zero.(May be basic to y'all, but maybe really usefull to someone else).

Here's a simple JavaScript solution to hide your e-mail from many spam scripts while still providing clickable hyperlinks to your visitors.

Web crawlers and visitors with JavaScript disabled will see: me [at] mydomain [dot] com. I've seen a lot of people that just leave it at this, but it seems a bit unprofessional in my opinion. With the following code, we can replace that with a fully functional hyperlink.

It works with Array types. The example is a simple list of numbers, but the array could contain anything; lists of strings, functions, DOM nodes, whatever. Unfortunately, a lot of things that seem like arrays in the DOM aren't really, so you can't shuffle the images on a page with just document.images.shuffle() all by itself.

To debug javascript code we use alert() whereever needed and it irritates you while alerts values inside a loop and other places where more alerts are being shown and you have to press the ok button to pass / proceed on.here is a simple way to get rid of the alerts dialogs and get the values outputed into another debug window.