Lesson 4 of 8
Where GTM Runs Your Code
GTM gives you two places to run JavaScript, and choosing the right one is half the battle.
Custom JavaScript variable
- A function that MUST return a value.
- Use it to compute or reshape data for a tag.
- Runs when the variable is read.
- Example: clean a price, build the items array.
Custom HTML tag
- A block of HTML/JS that runs on a trigger.
- Use it to do something: inject a script, add a listener.
- Runs when its trigger fires.
- Example: attach a custom event listener.
// Custom JS VARIABLE — always return
function () {
var raw = {{DLV - price}}; // reference other GTM variables with {{...}}
return Number(String(raw).replace(/[^0-9.]/g, ""));
}<!-- Custom HTML TAG — do something -->
<script>
(function () {
document.addEventListener('click', function (e) {
if (e.target.matches('.book-demo')) {
window.dataLayer.push({ event: 'demo_click' });
}
});
})();
</script>Rule of thumb: if you need a value, use a Custom JS variable. If you need an action, use a Custom HTML tag.
Key takeaway
Custom JS variables compute and return values; Custom HTML tags do things on a trigger. Pick by whether you need a value or an action.