2

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.

Josh Gomes
  • 193
  • 4
  • 16
  • 2
    Can you add the relevant HTML as it shows up in the source view of your browser? Also, the primary cause of events failing is that the element didn't exist yet when the listener is added. –  Mar 21 '18 at 14:31
  • Maybe try adding the event listener in jQuery("document").ready(function() {...}) ? – rogerrw Mar 21 '18 at 14:34
  • Hi @ChrisG sorry I have now made a JS fiddle with it: https://jsfiddle.net/e5dnru0e/3/ – Josh Gomes Mar 21 '18 at 14:47
  • 1
    @JoshGomes If you add jQuery to the fiddle and set the code to be at the and of ``, it works fine: https://jsfiddle.net/khrismuc/e5dnru0e/7/ –  Mar 21 '18 at 14:50
  • Thanks @ChrisG that might just be the thing! – Josh Gomes Mar 21 '18 at 14:54

1 Answers1

2

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');
    });
Tanmay
  • 1,123
  • 1
  • 10
  • 20