We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 32963
    • 1,732 Posts
    Hello Everyone,

    I’ve been playing around with the idea of separating my Javascript from my html codes and have used Ben Nolan ’s wonderful Behavior library.

    The basic idea is that you can group all your Javascript codes into one .js file and then take control of your html elements without having to write a single line js code inside your html pages. In short it’s called "Unobtrusive Javascript."

    For the most part it works great in a few applications that I’ve worked and should also work great in a new version of MODx that I’m working on.

    Here’s the info on the library:

    Behaviour v1.5
    ---------------------------------------------
    This is a modified version of Ben Nolan behaviour.js

    Description:

    Uses css selectors to apply javascript behaviours to enable
    unobtrusive javascript in html documents.

    Usage:

    var myrules = {
    	'b.someclass' : function(element){
    		element.onclick = function(){
    			alert(this.innerHTML);
    		}
    	},
    	'#someid u' : function(element){
    		element.onmouseover = function(){
    			this.innerHTML = "BLAH!";
    		}
    	}
    };
    
    Behaviour.register(myrules);



    Once your rules are registered you can Behaviour.apply() to re-apply the rules (if you update the dom, etc).

    To re-apply behaviour rules to a specific element use:

    var myElement = document.getElementById('div1');
    Behaviour.apply(myElement);



    Using the new oninit and onbeforesubmit events:

    Javascript code:

    Behaviour.register({
    
    	'form' : function(element) {
    		element.onsubmit = function(){
    			// let behaviour know that
    			// we are about to submit the form.
    			Behaviour.invokeOnBeforeSubmit();
    			return false;
    		}
    	},
    
    	'input#username' : function(element){
    		element.oninit = function(){
    			// this function will only be called once
    			this.value = 'Enter your name here';
    		}
    		element.onbeforesubmit = function(){
    			// this function is called when
    			// Behaviour.invokeOnBeforeSubmit is called
    			alert('You have entered:'+this.value);
    		}
    	}
    
    });


    HTML code:

    <form>
    <input type="text" id="username" name="username" size="30" />
    <input type="submit" value="Submit" />
    </form>

    You can download it here:

    http://www.xwisdomhtml.com/downloads/behaviour1.5.zip
      xWisdom
      www.xwisdomhtml.com
      The fear of the Lord is the beginning of wisdom:
      MODx Co-Founder - Create and do more with less.