I am having trouble targeting elements within jQuery ui-datepicker with the plugin WooCommerce Bookings.
Every time I target it using JavaScript it returns null, so the EventListener can't be executed.
However, if I target anything outside the jQuery ui-datepicker I can actually execute the events created with the JS and jQuery.
This is the first time I have encountered something like this and I'm finding it very unusual.
There are the two snippets I have used to test whether or not it can identify the element:
jQuery('.hasDatepicker').on('click', function() {
alert('hi');
});
function showVolunteers() {
alert("hi");
}
document.querySelector(".hasDatepicker").addEventListener('click', showVolunteers);
Here is a JS fiddle with the HTML for the datepicker: https://jsfiddle.net/e5dnru0e/3/
The datepicker is nested within a fieldset, which I can target so I thought maybe I could try use jQuery('fieldset div.ui-datepicker') but that did not work either.
To triple check I was using the correct selector I tried using some CSS and the CSS works perfectly, so there isn't something wrong with my selector.
Is it possible that it has somehow restricted jQuery to be used within this datepicker.
Any help or suggestions will be greatly appreciated.
When your are registering an event for any DOM element then it should be present in DOM at the time of registering.
In case of dynamic controls (which are injected to DOM after DOM ready event) you can use following syntax of jquery for registering an event.
$(document).on('click','.ui-datepicker', function() {
alert('hi');
});
Above code attaching click event on document
(which is always present on Document ready). Second parameter of on
function is [selector]
ie. .ui-datepicker
Instead of document
, you can attach click event on any other DOM element which is going to
present while registering an event.
i.e
$('.datepicker-container').on('click','.ui-datepicker', function() {
alert('hi');
});