maddogandnoriko
maddogandnoriko

Reputation: 1002

Basic jQuery bind

I came to a point in my project where I am detecting arrow key presses and was using:

$(document).bind('keypress', function(event) {
    alert("Handler for .keypress() called.");
});

and was researching and found I could use this instead:

$(document).keypress(function() {
    alert("Handler for .keypress() called.");
});

I like the second one best, it looks cleaner. They appear to do the same thing. So...

Upvotes: 0

Views: 46

Answers (4)

ajp15243
ajp15243

Reputation: 7952

The jQuery docs are your friend!

  • .bind() is being deprecated, so as suggested here, you should not use it if you're using jQuery 1.7+.
  • .on() is the preferred way of attaching event handlers in jQuery 1.7+.
  • .keypress() is one of a number of "special", specific event attachers (most of which usually call .on() or .bind() anyway) and, according to the docs, may have different behavior across browsers, browser versions, and platforms.

Given the info on those three functions, your best bet should be to use .on().

Upvotes: 1

Dogoku
Dogoku

Reputation: 4675

The .keypress() or any other similarly named function .click(), .hover() etc are just shorthands for the .on() function

Upvotes: 1

BLSully
BLSully

Reputation: 5929

It's mostly personal preference. You're right, they do both do the same thing... however, they've been deprecated in recent versions of jQuery

As Andrew mentioned in your comment, use on, not bind.

on gives you the additional benefit of being able to use the same function to bind delegate handlers for elements that may or may not exist at the time the bindings are initialized:

$('#someExistingElement').on('keypress', handler); //normal binding

$('#someExistingElement').on('keypress', '.some-child-element-that-doesnt-exist', handler); //delegate binding

Please excuse the horrendous class names and id's...demo purposes only :D

Upvotes: 0

Jamiec
Jamiec

Reputation: 136104

The two examples you give do indeed do the same thing - both of which are pretty much deprecated as of jQuery 1.7

From http://api.jquery.com/bind/

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

These older methods of attaching an event handler required that the elements existed in the DOM when the event handler was attached. There are smarter (not to mention more efficient) ways of doing the same with more recent versions - and this is generally refered to as delegation. You should check out .on()

Upvotes: 1

Related Questions