I'm a digital analyst and am attempting to learn Javascript, especially as our organization now uses Google Tag Manager.
This morning my site was set to track certain outbound links (clicks to the app store) as events. The custom HTML was:
<script type="text/javascript">
$(document).ready(function(){
$('.app-cta a').click(function(){
dataLayer.push({ 'event':'GAevent', 'eventCategory':'App', 'eventAction':'Click to App Store', 'eventLabel':'iOS' })
});
});
</script>
But there was an issue (apparently pretty common) where when an individual clicked the exit link, the browser hit the new site before the Javascript had time to pass the parameters to Google Analytics. The suggested workaround was to add a 500 millisecond delay thus:
<script type="text/javascript">
setTimeout(function(){
$(document).ready(function(){
$('.app-cta a').click(function(){
dataLayer.push({ 'event':'GAevent', 'eventCategory':'App', 'eventAction':'Click to App Store', 'eventLabel':'iOS' })
});
});
},500);
</script>
This worked which made me feel great because it's the second or 3rd time I'd ever used Javascript.
Then I wanted to be a little bolder. I wanted to make the code "neater" and tried to create a variable out of the analytics function, then run setTimeout method against that variable. This is what I tried:
<script type="text/javascript">
setTimeout(function(){track_app},500);
var track_app = $(document).ready(function(){
$('.app-cta a').click(function(){
dataLayer.push({ 'event':'GAevent', 'eventCategory':'App', 'eventAction':'Click to App Store', 'eventLabel':'iOS' })
});
});
</script>
I realize that this must appear very basic but I'd be grateful if someone could point out why this last attempt did not work? Was my initial attempt (That was working and that I could easily revert to) the "neatest" way of adding the 500 millisecond delay to the analytics function? What would be the best way to integrate the setTimout method?