Applying JavaScript to CSS Selectors


Behaviour.register(cssrules); 

In 1999, the W3C proposed "Behavioral Extensions to CSS (http://w3.org/TR/1999/WD-becss-19990804), an approach to bind JavaScript code to CSS behaviors. The basic idea was to avoid use of the well-known onxxx HTML attributes. After 1999, not much progress was made in this area, but Ben Nolan managed to provide a workaround (read: hack) to allow a similar concept. For it to work, you need the JavaScript library from http://www.bennolan.com/behaviour/, in form of the file behaviour.js. (Note the British English spelling of the worda perfect addition to the phrasebook!) This code collection allows providing rules containing JavaScript code in the form of CSS selectors.

For it to work, you first need an external JavaScript file that defines CSS rules. You basically create an object with CSS selectors as the keys, and JavaScript event-handling functions as the values. Then, you call the Behaviour.register() method to report these rules to the behaviour library:

The CSS/JavaScript Rules (rules.js)

var cssrules = {   "p.para" : function(e){      e.onmouseover = function(){        this.style.fontWeight = "bold";      }      e.onmouseout = function(){        this.style.fontWeight = "normal";      }   },   "#term" : function(e){       e.onmouseover = function(){         this.style.fontStyle = "oblique";       },       e.onmouseout = function(){         this.style.fontStyle = "normal";       }     }   }; Behaviour.register(cssrules); 

All that is left to do is to load both the JavaScript library and the preceding rules JavaScript file. Then the JavaScript code is executed when the associated events (in the example: mouseover and mouseout) are fired.

Using the Behaviour JavaScript Library (behaviour.html)

<script language="JavaScript"   type="text/javascript" src="/books/3/490/1/html/2/behaviour.js"> </script> <script language="JavaScript"   type="text/javascript" src="/books/3/490/1/html/2/rules.js"> </script> <p >CSS <span >and</span>   JavaScript</p> 

Figure 4.4 shows the result: When the mouse pointer is moved over the <span> element, two event handlers are called.

Figure 4.4. The JavaScript code gets executed.


Note

The main advantage of this approach lies in the fact that the JavaScript code completely resides in external files and is not cluttering the HTML markup of the page. From an architectural point of view, this is quite a bright ideaand it works cross-browser.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net