Form substitution depending on UTM label
Hi!
We recently received a request from a client to help us implement a functionality whereby users who have navigated to a site with a certain UTM tag display one form, and everyone else - another form.
How do you change the form on your site depending on the UTM tag?
We didn't have a ready solution for this and decided to show how it can be implemented at any site using JavaScript code.
In order to read the GET parameter value from the URL, we have a special URL() object in javascrpt that provides convenient methods and parameters to manipulate the URL.
In order to create this object you need to pass the current URL string to the constructor of this class. You can do it like this:
var url = new URL(document.location.href);
searchParams property of the URL object. To get the UTM value of the utm_source tag, you need to write the following code:
var utmSource = url.searchParams.get('utm_source');
Having received this value, we can now compare it to the given value and replace the form ID, with any other value. As an example, let's replace the form for visitors who clicked on the site with a UTM tag utm_source equal to the value "promo":
<div id="form_123456_1"></div> <script type="text/javascript"> (function (d, w, c) { var url = new URL(document.location.href); var utmSource = url.searchParams.get('utm_source'); // ID формы по умолчанию var formId = 123456; // ID формы, для пользователей с UTM меткой utm_source равной promo if (utmSource === 'promo') { var formId = 654321; } (w[c] = w[c] || []).push({formId: formId, host:"formdesigner.ru", formHeight:100, el: "form_123456_1", center: 1, scroll: 0}); var s = d.createElement("script"), g = "getElementsByTagName"; s.type = "text/javascript"; s.charset="UTF-8"; s.async = true; s.src = (d.location.protocol == "https:" ? "https:" : "http:")+"//formdesigner.ru/js/iform.js?v=0.0.2"; var h=d[g]("head")[0] || d[g]("body")[0]; h.appendChild(s); })(document, window, "fdforms"); </script>
By default, form ID = 123456 will be shown for all visitors, and form ID = 654321 will be shown for those users who visited the site with promo utm_source.
This is how easy it is to make the form swap depending on the UTM tag value.