Tracking form button submit events
thewaliii opened this issue · 5 comments
thewaliii commented
I don't have control to add attributes to the submit buttons, but I can add attributes to the wrapper or parent element of the form on my website.
What can I change in the code for this to work?
<script>
let buttons = document.querySelectorAll("button[data-analytics]");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', handleFormEvent);
buttons[i].addEventListener('auxclick', handleFormEvent);
}
function handleFormEvent(event) {
event.preventDefault();
let attributes = event.target.getAttribute('data-analytics').split(/,(.+)/);
let events = [JSON.parse(attributes[0]), JSON.parse(attributes[1] || '{}')];
plausible(...events);
setTimeout(function () {
event.target.form.submit();
}, 150);
}
</script>
RobertJoonas commented
Hi @Waleedov!
The following code should work if the <form>
element is the only child of the wrapper <div>
:
<div data-analytics='"My Event Without Properties"'>
<form>
<button type="submit">Send Message</button>
</form>
</div>
<div data-analytics='"My Event",{"props":{"my_property":"some_value"}}'>
<form>
<button type="submit">Send Message</button>
</form>
</div>
<script>
let wrapperElements = document.querySelectorAll('div[data-analytics]')
for (var i = 0; i < wrapperElements.length; i++) {
let wrapper = wrapperElements[i]
var form = wrapper.children[0]
let attributes = wrapper.getAttribute('data-analytics').split(/,(.+)/);
let eventName = JSON.parse(attributes[0])
let eventOptions = JSON.parse(attributes[1] || '{}')
eventOptions.callback = function() { form.submit() }
form.addEventListener('submit', function(event) {
event.preventDefault();
setTimeout(eventOptions.callback, 5000);
plausible(eventName, eventOptions)
})
}
</script>
Hope this helps!
thewaliii commented
Thanks, to be exact, this is the structure:
<div class="parent" data-analytics='"My Event Without Properties"'>
<div class="child">
<form>
<button type="submit">Send Message</button>
</form>
</div>
</div>
Can you please adjust the code? sorry I am very noob in JS.
RobertJoonas commented
No worries! Will your <div class="child">
be only child of <div class="parent" ... >
too? In that case you can do:
var form = wrapper.children[0].children[0]
instead of:
var form = wrapper.children[0]
thewaliii commented
Thank you. Where can I ask for premium support? Someone to check my website, dashboard etc..?
metmarkosaric commented
hi @Waleedov! you can reach our customer support here