4

Possible Duplicate:
jQuery 1.7 - Turning live() into on()
.live() vs .on() method

I have the following code (which I've simplified for this) which worked fine alongside jquery-1.7.

$("td.ui-datepicker-week-col a").live("click", function () {
    alert("hello");
});

I'm trying to upgrade my code though so I can upgrade my jQuery pack version so I've changed it to this.

$("td.ui-datepicker-week-col").on("click", "a", function () {
    alert("hello");
});

This doesn't do anything though. It doesn't throw any errors either so I can't see where the problem is.

Any ideas?

Community
  • 1
  • 1
Tom
  • 12,776
  • 48
  • 145
  • 240

5 Answers5

9

If you don't have "td.ui-datepicker-week-col" element at start, then you must choose an existing permanent set. For example

$(document).on("click", "td.ui-datepicker-week-col a", function () {
    alert("hello");
});

The on function, contrary to live, will only work with the set as it is defined when you call the binding function. What is dynamic is the interpretation of the selector passed as argument to on when an event occurs.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • You got a typo, there's one quote too much before `td.ui-datepicker-week-col`. – 11684 Jan 16 '13 at 16:05
  • despite the typo (which I'm sure you'll edit), a great answer explained well enough for simpleton me to understand. Thanks – Tom Jan 16 '13 at 16:07
3

The first part of your on statement binds to elements that already exist at the time of the call. To properly use delegation, you need to pick an element that exists at the time, and is guaranteed to be a parent element of the event element. If nothing else, you can always use document (this is what live did, too!)

$(document).on("click", "td.ui-datepicker-week-col a", function(e) { /*...*/ });
Plynx
  • 11,341
  • 3
  • 32
  • 33
1
$("body").on("click", "td.ui-datepicker-week-col a", function () {
    alert("hello");
});
ek_ny
  • 10,153
  • 6
  • 47
  • 60
1

The problem may be that "td.ui-datepicker-week-col" was not present at the DOM at the time the page was loaded and the on event attached.

Attach the handler to an parent element, which will be there at the time of the javascript code load. The simplest (and worse, but working) is:

$("body").on("click", "td.ui-datepicker-week-col a", function () {
  alert("hello")
})

This will be triggered for every click on document, then jQuery will verify if the clicked element is "td.ui-datepicker-week-col a" and, if true, execute the callback.

A more efficient way to do this is to attach to an existing subcontainer in which "td.ui-datepicker-week-col a" will be for sure.

fiatjaf
  • 11,479
  • 5
  • 56
  • 72
0

Try this...

$('.ui-datepicker-week-col').on('click', 'a', function () {
    alert("hello");
});

And see this Example

Greetings.

MG_Bautista
  • 2,593
  • 2
  • 18
  • 33