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
- I am using the latest version of jQuery.
- No JS Errors are thrown.
- HTML is valid
- The a.x-btn selector is being found (length = 2)
- console.log(‘Got this far!’) is firing correctly.
- console.log(‘Sidebar Cal Clicked’) not firing at all.
- Running in a WordPress environment.
- DOCTYPE is set for HTML5
//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!
I think this stems from the pre-evaluation of
s.find
. Does using this code give you different results?I suspect there mibht be some problem here
There shouldn’t be any issue with live click.
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…”
The problem I think is here:
It’s not returning correct element.
Could this be caused by you having a nested document ready? Can you remove the second one?
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)