I was reading klaviyo’s integration guide. The javascript it is using to submit form data is:
<script type="text/javascript">
$("input[name='contact[email]']").on('blur', function(e) {
e.preventDefault();
var email = $(this).val();
var settings = {
"async": true,
"crossDomain": true,
"url": "https://manage.kmail-lists.com/subscriptions/external/subscribe",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache"
},
"data": {
"g": "LIST_ID",
"$fields": "$source",
"email": email,
"$source": "Shopify form"
}
};
$.ajax(settings).done(function (response) {
console.log(response);
});
});
</script>
I am wondering why it is using the “blur” event instead of user’s clicking on “submit” button to trigger the ajax function. I think with this code, if user opt out of the form’s text-box prematurely without clicking “sign up” or “submit”, the data will be submitted.
2
Answers
The blur event fires when the element loses focus and potentially ‘after’ the email is typed in it gets sent. This is helpful with conversions from dropoffs in general.
“I am wondering why it is using the “blur” event instead of user’s clicking on “submit” button to trigger the ajax function.”
Because this two ways will give you two different behaviors. Very simple:
click
event, the function will be executed after button clickblur
event, the function will be executed after the input will lose it’s focus