I have a website built in WordPress which is using the "BWL Knowledge Base Manager" plugin which provides an AJAX search bar.
Our SEO Manager has provided us with the following tracking script which needs to be triggered when someone enters a search string into the search bar:
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'search'
'Dlv-Search': 'ger', //recorded under “s”
});
</script>
(Where, obviously, ‘ger’ is to be replaced with whatever the user has entered into the search field).
It turns out that I have very little idea of how to implement this. Can anyone point me in the right direction here?
2
Answers
Ah hah! So it appears that the plugin is somehow generating the search input field after the DOM is initially loaded. So this appears to have done the trick:
I have created the function (Thanks Xhynk for the suggestion):
And then I have added the following to my child-theme's footer.php file:
So now it is waiting and checking to see when "#s" is actually ready before trying to do anything with it.
This code looks more intimidating than it is. You should be able to add it straight to your search bar, perhaps on the
keydown
oronchange
events. It may be cleaner if you wrap it in a function though.Then just add that function to your input on whatever event you want to handle it on:
Edit:
Since you’re unable to modify the HTML of the input, you should be able to bind an event handler to it instead. Check out this snippet:
Run the snippet, and the
change
event will log the dataLayer variable as soon as you tab away or click. Thechange
(onchange
) events require you to leave the field. You may need to usekeydown
orkeyup
or something, but that can create a LOT of function calls, at which point you’d need to look at using a typing timeout or something.