Highlighted

Tracking events via jquery and data attribute

Bronze Contributor
Bronze Contributor

I plan to build an extension to track events where an attribute is placed on a link or button. As recommended in the following blog post (https://tealium.com/blog/tag-management/ajax-tracking-urls-longer-change/).  

jQuery('.button').click(function(e) {

utag.link( jQuery(this).data('info') );

});  

 My question is how do I make the event fire on button click only when the click passes a successful validation.  So thinking of a form submit someone can click the button but all the form field may not be valid so the success event may not occur.  Is there a way to include something to wait for a success flag before sending?

 

1 REPLY 1
Highlighted

Tracking events via jquery and data attribute

Tealium Expert
Tealium Expert

At the point of the click itself, @JoeBrown, the page may not know if validation has been passed.

The most elegant solution would be to integrate directly with the form validation scripts and have those invoke your event upon successful validation. But obviously that's not always possible.

The easiest way to do it would be to introduce a quick timer to delay the event until you've got confidence that the validation has run. The length of the delay would depend on whether the validation is performed live on the page, or as the result of an AJAX call, but it might look something like this:

jQuery('.button').click(function(e) {
  fireIfValid( jQuery(this).data('info') );
});

function fireIfValid(payload){
  setTimeout(function(){
    if(jQuery(".inputErrorClass").length == 0){
      utag.link(payload);
    }
  }, 10);
}

This assumes that the validation routine might, for example, highlight invalid fields by applying an "inputErrorClass" class to the field. Your exact solution will obviously vary, but the idea would be to be able to use jQuery to determine whether the page is in an error state or not after a suitable delay, and only transmit the data if it's not.