Reputation: 4810
I have an ajax calendar which changes the month when some arrows are clicked. For some reason, the click event is not working within the live() method. It used to work, but now it does not for some reason.
If I replace live() with click() it works, but I need the live() method.
Assumptions
//ajax calendars
jQuery(document).ready(function($) {
//sidebar
$(function() {
var s = $('#s-calendar'), p = s.closest('.widget');
console.log('Got this far!');
//prevent collapse
p.css('min-height', p.height());
s.find('a.x-btn').live('click', function(e) {
console.log('Sidebar Cal Clicked');
var d = $(this).attr('data-cal-date'), n = $(this).attr('data-nonce');
var url = $(this).attr('data-ajaxurl');
$.ajax({
url:url,
type:'POST',
data:'action=wpcal&sidebar=true&_wpcal_nonce='+n+'&date='+d,
success:function(data) {
s.fadeOut(500, function() {
s.html(data).fadeIn(500);
});
}
});
return false;
});
});
});
ANSWER
Turns out another piece of JS was causing the live not to work. The live() method requires event propagation in order to work correctly. I had a small line of JS at the top of my code which I sometimes find useful.
$('body a[href=#]').click(function(event) { event.preventDefault(); });
I use that code to prevent the page from jumping when useless links are clicked. This ends the propagation on all 'A' tags that with href="#" when they are clicked. I removed it and everything works fine.
In addition, despite what the jQuery Docs say, using jQuery 1.5.2, the live() method works after DOM traversal. I went ahead and changed it anyways, just to be inline with the documentation. But it does work! Thanks for the help guys!
Upvotes: 3
Views: 9917
Reputation: 1
The live() function has been removed for jQuery versions > 1.9. Try something like, $('#button_id').on('click', 'button_tag_type', function) or $('body').on('click', '.Button_class', function)
Upvotes: 0
Reputation: 17825
Could this be caused by you having a nested document ready? Can you remove the second one?
//ajax calendars
jQuery(document).ready(function($) {
//sidebar
$(function() { // remove this one
Upvotes: 0
Reputation: 2481
See caveats for live: http://api.jquery.com/live/#caveats
Specifically:
"DOM traversal methods are not supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector..."
Upvotes: 1
Reputation: 15835
I suspect there mibht be some problem here
s.find('a.x-btn')
There shouldn't be any issue with live click.
Upvotes: 1
Reputation: 21439
The problem I think is here:
s.find('a.x-btn')
It's not returning correct element.
Upvotes: 0
Reputation: 17825
I think this stems from the pre-evaluation of s.find
. Does using this code give you different results?
$('#s-calendar a.x-btn').live('click', function(e) {
Upvotes: 3