user3615851
user3615851

Reputation: 990

Adding Google Analytics event to form submit

I'm looking to add a Google Analytics event to a form that I can not access the inline html, so I can not add it as a onClick="" event straight to the html.

So my solution has been so far:

    $(function() {
  $(".form_submit input").on("click", function() {
    dataLayer.push({
      "event": "Kontakt",
      "eventCategory": "Submit",
      "eventAction": "Kirjuta meile",
      "eventLabel": "Kirjuta meile"
    });
  });
});

Althought this does not seem to work as clicking the submit button possibly stops all functions and refreshes the page.

How can I run the function before submit and then submit the form after? I've been suggested using preventDefault(); and the after calling the submit again with $('form').one('submit', ... but have been unable to implement this due to lack of skill.

View site: http://avrame.com/en (the form is at the bottom of the page)

Any suggestions appreciated.

Upvotes: 1

Views: 6025

Answers (2)

user3615851
user3615851

Reputation: 990

Working solution ended up using this callback method:

var form = document.getElementsByClassName('.footer__contact form');
form.addEventListener('submit', function(event) {

  event.preventDefault();

  setTimeout(submitForm, 1000);

  var formSubmitted = false;

  function submitForm() {
    if (!formSubmitted) {
      formSubmitted = true;
      form.submit();
    }
  }

  ga('send', 'event', 'submit', 'Saada', 'Kirjuta meile', {
    hitCallback: submitForm
  });
});

Reference from: https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits#hitcallback

Upvotes: 1

Viktor Tabori
Viktor Tabori

Reputation: 2207

You can actually push functions to dataLayer, and it will be executed after the first event.

I would do

  • delegate the submit watch event to document level (see Jquery .on() submit event)
  • intercept the first submit, pushing event and preventing default behavior
  • and insert a function inside dataLayer, which submits the form again, but this time it won't be halted

The code:

window.submitGA = false;
$(function() {
  $(document).on('submit','.form_submit',function(event){
    if (!window.submitGA)
    {
      window.submitGA = true;
      dataLayer.push({
        "event": "Kontakt",
        "eventCategory": "Submit",
        "eventAction": "Kirjuta meile",
        "eventLabel": "Kirjuta meile"
      });
      dataLayer.push(function(){
        $('.form_submit').submit();
      });
      event.preventDefault();
    }
  });
});

Upvotes: 3

Related Questions