I’m trying out something new here, every week i’m going to write a short post describing an HTML_AJAX feature. Hopefully this will get some people started using the new features and maybe even get some more developers helping out with the project. It will also give me a place to try out some material for my upcoming AJAX book.
I also used the American spelling of Behavior instead of the British (darn extra u’s)
Turning Behaviors on
Assuming you already have HTML_AJAX installed all you need to use behaviors is add “behavior” to your list of libraries.
If you just wanted the behavior library you could do:
Or including it with some of the other HTML_AJAX pieces
Adding Behavior Rules
An example rule is shown below:
Now this rule is rather worthless since its just setting a style rule, something that css is much better suited for but it does show a couple important things. You have immediate access to the matching elements, this allows you to create new child elements, update properties including innerHTML, and set event handlers.
You can set event handlers using onEvent methods but i prefer to use a couple util methods in HTML_AJAX that map to setEvent etc.
A more useful example which submits all the forms on a page using AJAX is shown below:
There isn’t a lot too see here, we build a function to handle the submit event. It submits the form using HTML_AJAX.formSubmit, the first param is the form to submit, the second is the element to update (The second element is optional but do a bug in 0.3.3 it not being set isn’t detected correctly so you’ll have to upgrade to 0.3.4 to skip it). Then we cancel the normal form submission.
Wrapping it up
These examples show some of the power of behaviors, but there really is a lot more that you can do with it. If you have any tips feel free to leave them on the wiki or as comments to this post.