Add an event listener to form that removes event listener even with use of Event Delegation

gerard_reyes Posted by: Gerard Reyes Date Posted: May 27, 2024
Back to Case Studies

Issue

The client has a complicated form setup.

  1. It is a three-page form. Technically, it is not a form but just a series of divs.
  2. With every page movement, the inputs disappear, creating a new set of inputs.
  3. The most problematic, for some reason, is that you cannot register an event to a button even when using Event Delegation does not work.

Solution

I attached the event to the on-change event of the email input instead. This actually works because we will only want to capture a lead with an email, so the email input is the perfect place to set it up. I also added a checking mechanism to check if the event listener has already been added. This prevents duplicate issues that might arise by firing multiple times.

setInterval(function() {
     jQuery('input[id^="bookly-email-"]').trigger('change');
}, 1000);

var counter = 0;
jQuery(document).on('change', 'input[id^="bookly-email-"]', function(event) {
     if (counter === 0) {
         console.log('Capture lead event listener added');
         counter = 1;
         jQuery('button.bookly-js-next-step').on('click', function(event) {
             // Your code here
         });

         jQuery('button.bookly-js-back-step').on('click', function(event) {
             counter = 0;
         });
     }
});

Achievement

Can fire a faux form to capture the lead.

Snippet/Screenshot/Link

Ticket: Link