applying events like css with jquery January 14, 2008
I've been using jQuery a lot recently and I've only got positive remarks about it. Here's a code snippet I use with most of my projects to apply events similar to CSS (inspired by lowPro).
// the initial code
Here's the code:
var initEvents = function(behaviors){
/* Add behaviors to the document when it's ready */
$(document).ready(function(){
var ruleAndEvent, rule, event, key, fn;
for(key in behaviors){
fn = behaviors[key];
ruleAndEvent = key.split(":");
rule = ruleAndEvent[0];
event = ruleAndEvent[1];
$(rule)[event](fn);
}
});
}
// how to use initEvents
initEvents will loop through a Javascript dictionary, where the key is a string in CSS selector format and the values are functions. Here's a sample of how to use it:
initEvents({
'a.hello:click': function(event){
event.preventDefault();
alert('Hello World!');
},
'form.thanks:submit': function(event){
alert("Thanks for submitting the form!");
}
});
Now any links with class 'hello' will say "Hello World" when clicked. Any forms with class 'thanks' will thank the user after submitting.