I like the way jQuery wraps events when you use its "bind" method. However it's awkward to set up the bindings. Is there any way to combine the ease of html (e.g. onKeyPress="foo(event)" ) with jQuery's browser-independent event-handling goodness?
3 Answers
You mean like this?
function foo(event) {
alert(event.target);
}
$('.someSelector').keypress(foo);
Whether in HTML or javascript way you need to create a function foo, so maybe this is closer to what you were looking for.
I'm not sure what exactly you feel is awkward about jQuery's handler binding.
5 Comments
on[event] attributes, then use the value of the attribute as needed.You probably don't want to do that.
You may want to read up on event delegation in JavaScript, which those jquery binding methods handle neatly for you.
Here's the highlights:
Event delegation has several benefits to the performance of a web application:
Fewer functions to manage. Takes up less memory. Fewer ties between your code and the DOM. Don’t need to worry about removing event handlers when changing the DOM via innerHTML.
You're better off using jQuery's binding helpers like $whatever.click(fn) etc.
Actually here is another question on SO that references the same article I did that may also help.
Comments
A good idea is to actually separate the two, to have your HTML clean and the js in a separate location. You can try shortcuts like $('a').click(...) instead of $('a').bind('click'...), but that's about it. Personally I like having the bindings separate from the markup.
on[event]attributes. So you're really looking at one or the other.