As promised here are some concrete example of unobtrusive JavaScript, versatile and powerful tool if used properly. On Site / Blog Ryan Johnson you can download two very good example of unobtrusive JavaScript:
Ryan Johnson, in his script, the library uses Prototype , like many of the rest. He has also written some extensions to the relatively Prototype , then introduced - in a different form - in the latest version of the library.
Use Prototype to illustrate the operation of unobtrusive JavaScript code is generally more convenient - as we shall see later, however, here is a first example crude which requires no external libraries. We begin by recalling that the concept behind the unobtrusive JavaScript is to start from any HTML page (standard and not necessarily written by us - more important strong point) and use Javascript to make some changes.
Schematimamente the concept is to perform a function that parses the HTML, then traverses the DOM and in particular points to add or change functionality. Normally utilize two methods to execute Javascript code to load a page: the first is what you do not enclose the code in any function, and then let the browser execute code immediately uploaded to the point where the call appears:
The same result is obtained by including the code:
1
| "http://miosito.com/miocodice.js" >< / script > < script src = "http://miosito.com/miocodice.js"> </ script > |
However, when it must operate on the DOM of a page that it assumes a fully loaded, that all the TAG of the page is present and available to be tracked. So the best solution becomes the one to be sure that the page is complete. This is possible by engaging the onload event of body tag, for example, which is released when the page load is complete.
1 2 3
| miafunzione ; window. onload = myfunction; / / Or, which is the same function ( ) { alert ( "Hello" ) ; } window. onload = function () {alert ("Hello");} |
Be avoided, of course, the canonical solution that would be an understatement to call it intrusive:
1
| "miafunzione()" > < body onload = "myfunction ()"> |
Another technique, more coarsely and equally intrusive (as it would force the end user to place the code in a particular spot), is to insert our script at the end of the document before the closing body tag, now obsolete technique and used in rare cases (see Google Analytics!).
Even better is to use the method below:
1 2 3 4 5 6 7
| window. addEventListener ) { if (window. addEventListener) { "load" , miafunzione , false ) ; window. addEventListener ("load", myfunction, false) ¾ Í ( window. attachEvent ) { } Else if (window. attachEvent) { "onload" , miafunzione ) ; window. attachEvent ("onload", myfunction) ¾ Í { Else {} createSubMenus; window. onload = createSubMenusÍ ¾ } |
Even this piece of code is enclosed in a function. It will add an event listener for the load event of the window, calling our function miafunzione() . . Modern browsers such as FireFox for example, will use the function addEventListener() defined in DOM Level 2, while Internet Explorer will use its proprietary function attachEvent() . However we are not at perfection in this way, in fact, it will replace all - if any - onload events created by other scripts, which is not really "non-intrusive."
To resolve this issue quickly, that because of the different behavior of the browser would be least complicated to explain here, you should use as libreirie Prototype providing un'elengantissimo method to overcome the problem:
1
| window , 'load' , function ( ) { alert ( "Hello" ) ; } ) ; Event. Observe (window, 'load', function () {alert ("Hello");}); |
The syntax is very obvious and spectacular! The advantage for those who had not understood, is that you can write:
1 2
| window , 'load' , function ( ) { alert ( "Hello 1" ) ; } ) ; Event. Observe (window, 'load', function () {alert ("Hello 1");}); window , 'load' , function ( ) { alert ( "Hello 2" ) ; } ) ; Event. Observe (window, 'load', function () {alert ("Hello 2");}); |
On loading the page will be shown before the alert "Hello 2" and then the alert "Hello 1". Basically you load in a FILO (First Last Input Output) a stack, while ensuring the execution of all events hooked to load the document exactly what was desired. In this way a page can load - virtually - endless unobtrusive JavaScript that hook to load the document.
But what can you do with this technique? Many interesting things. An example that we can comment (see also Prototype: the use of the double dollar sign ($ $) ) comes from Tobie Langel . With few lines of code and downloading libraries Prototype and Scriptaculous you can give a nice effect to the classic anchor of our pages. First create an HTML page with the following code:
1 2 3 4 5 6 7 8
| = "#capitolo1" > Vai al capitolo 1 < / a >< / p > < p > < a href = "# chapter 1"> Vai in Chapter 1 </ a > </ p > < / p > < p > </ p > < / p > < p > </ p > .... < / p > .... a lot 'of < p > </ p > .... just as an example "capitolo1" > Capitolo 1 < / h1 > < h1 id = "chapter 1"> Chapter 1 </ h1 > |
Include the page:
1 2 3 4 5 6 7 8 9 10 11 12
| "prototype.js" type = "text/javascript" charset = "utf-8" >< / script > < script src = "prototype.js" type = "text / javascript" charset = "utf-8"> </ script > "scriptaculous-js-1.7.0/src/effects.js" type = "text/javascript" charset = "utf-8" >< / script > < script src = "scriptaculous-js-1.7.0/src/effects.js" type = "text / javascript" charset = "utf-8"> </ script > "text/javascript" language = "javascript1.2" > < script type = "text / javascript" language = "JavaScript1.2"> Event.observe (window, 'load', function () { $ $ ('A [href ^ = #]: not ([href = #])'). Each (function (element) { element.observe ('click', function (event) {new Effect.ScrollTo (this.hash.substr (1)); Event.stop (event); bindAsEventListener (element)) }) }) </ script > |
Thanks to "use Event.observe() function and two-dollar ($ $) you can easily modify the behavior of the classic anchor. In this case a new function is hooked to the HTML page loads. When taking the load event is traced all the links in the DOM (Tag <A>) with href that begins with a pound (#, excluding the one with only hash!). To these elements is a function attached to the click event, similar to what was done with the load of the document. At this point comes into play Scriptaculous which produces an effect of the scroll towards the element punatato from our link - modified!
More ...
Allowing users to interact with a Web page in recent years has produced a significant increase in the use of client-side scripting: Javascript code can respond in real time and manipulate a variety of information. The Web2.0 is the ultimate expression of this capacity for interaction, in which the end user - the user-to participate actively in the construction and 'evolution of the Web site, interacting with it and helping yourself. Is referred to as User-Generated Content (or UGC - user generated content) that sees the "navigator" definitely not passive!
To achieve this interaction, thus allowing the end user to add his contribution, we developed a series of techniques that have changed the appearance and behavior of Web pages (static until now, but now similar to the traditional applications of Desktop) in recent years. Change the content of a page, send files, giving their vote to a video or a document, register or change their personal data, are just some of the adaptions operations in many services (2.0 beta) on the Web
More ...
Choose the technology to use in developing a Web Application is of vital importance, not to find himself in trouble soon after. The type of web application, its operational characteristics, are the first point to be taken into account to choose the FrameWork and related technologies.
I have often discussed the effectiveness of JavaScript script against different technologies like Adobe Flash or Java. However, it is important to emphasize an important aspect often overlooked: access to the DOM. Javascript, in this case, the candidate (if not the only one) a favorite for this type of operation.
Tools with Snap , for example, operate on a simple mechanism: when the HTML page is loaded (and after introduction of the loading of JavaScript scripts) is to scan the page and added a new HTML code at special points. In the case of Snap identifies all links to external pages (or in the internal configuration of the last issue), the TAG <A> for indenderci. These are modified so that on mouse to open a dialog anterpima of links (see this very blog for an example).
Not only snap but many other JavaScript scripts basically do the same thing. Lately, this technique is widely used by the library Prototype , which provides a variety of methods (such as the famous double-dollar, or $ $ $ - see Prototype: the use of the double dollar sign ($ $) ) is to track that change - the fly - the elements of an HTML page.
Navigating through the HTML DOM is therefore specific task of Javascript. Historically, inter alia, JavaScript was introduced in order to read and write the contents of an HTML page.
For example, if we wanted to make some changes to an HTML page using Adobe Flash, we aggorgeremmo - sooner or later - to be forced to invoke a JavaScript function. The new ActionScript 3.0, for example, provides a class ( ExternalInterface ) suitable for this purpose. – o fscommad() per chiamare una funzione Javascript: Once (in previous versions of ActionScript) we used the command getURL() - now replaced by better flash.net.navigateToURL() - or fscommad() to call a JavaScript function:
1
| ) ; getURL ("javascript: myFunction ()"); |
In addition:
The ExternalInterface class is the External API, an application programming interface That Enables straightforward communication Between ActionScript and the Flash Player container, for example, an HTML page with JavaScript, or a desktop application with Flash Player embedded.
Note that "desktop application" that so much reminds Apollo!
Today, thanks to ExternalInterface , you can invoke a JavaScript function to at least cleaner (this class allows management much more effective than getURL() , such as passing parameters):
1 2 3 4 5 6
| / * Calls the external function "addNumbers" passing two parameters, and Assigning That function's result to the variable "result" * / uint = 3 ; var param1: uint = 3; uint = 7 ; var param2: uint = 7; uint = ExternalInterface . call ( "addNumbers" , param1 , param2 ) ; var result: uint = ExternalInterface . call ("addNumbers", param1, param2); |
1 2 3 4 5 6
| <Script> <! - / / Adds two numbers, and sends the result back to ActionScript num1 , num2 ) { addNumbers function (num1, num2) { num1 + num2 ) ; return (num1 + num2); } / / -> </ Script> |
What can we conclude then? Among the various frameworks and libraries available the initial analysis of the project you want to achieve is of paramount importance. Mistakes at this stage can seriously affect the subsequent stages of any project Web2.0. JavaScript, then, that trumps all when it needs to interact with the DOM.
More ...
With the latest release of Prototype, Andrew , and Christophe have speeded up and improved the 'double dollar' ( $ $ utilities ), which allows you to select an item by specifying the dial (almost all CSS3 selectors supported by the specifications).
The usefulness of this feature goes beyond the popular $, which can be helpful but, ultimately, does not perform any operation worthy of note. The utilities 'two dollar' ($ $) but actually allows you to select any type of item, giving you great tools to filter elements in the DOM.
Here are some examples taken from the official site:
1 2 3 4 5
| ) ; // -> Tutti i DIV del documento. $ $ ('Div') / / -> All of the DIV document. Same as document.getElementsByTagName ('div')! ) ; // -> Uguale a $('contents'), ma ritorna sempre un array. $ $ ('# Contents') / / -> Same as $ ('contents'), but it always returns an array. ) ; // -> Tutti fli elementi LI con class 'faux' $ $ ('Li.faux') / / -> All fli LI elements with class 'faux' ) ; // -> Tutti i TAG A (links) al di sotto di un elemento con ID "contents" e con un attributo rel $ $ ('# Contents a [rel]') / / -> All TAG A (links) below for an element with ID "contents" and with a rel attribute ) ; // -> Tutti i TAG A (links) con un'attributo href con valore "#" (eyeew!) $ $ ('A [href = "#"]') / / -> All TAG A (links) with an attribute href value with "#" (eyeew!) |
The strength, however, lies in the possibility of excluding some items in favor of other, for example:
1
| ) ; // -> Tutti i TAG A (links), esclusi quelli che contengono un attributo rel impostato a "nofollow" $ $ ('A: not ([rel ~ = nofollow])') / / -> All TAG A (links), excluding those which contain a rel attribute set to "nofollow" |
Even more interesting is:
1
| ) $ $ ('A [href ^ = #]: not ([href = #])') |
This, in practice, all located in TAG with the href attribute that begins with '#' but does not take into account those that are equal to '#' only. In other words ignores the links that pointed to a valid ID!
This unique feature of ($ $) has inspired Tobie Langel to create a simple script (disarming) can add a nice effect when you scroll within a single HTML page you move to Anchors, with the technique - just - href = "#".
For a demo click here .
More ...
Latest Comments
Rosanna : Can anyone tell me how do I delete the Snap Shots window that opens automatically when I ...
blessed Maresca : I can not download any skypemote me spiegaaa
Matthew : Hello everyone, unfortunately Google does not allow the use of the API for Flash, but it will ...
Giovambattista Fazioli : @ GM: If you upload images to a different server (that WordPress can not ...
GM : Hi, sorry to resurrect an old post but I hope you can give me a hand. How do I, with this method, ...