{"id":123584,"date":"2025-03-10T05:57:07","date_gmt":"2025-03-10T05:57:07","guid":{"rendered":"https:\/\/peraltafinancing.com\/analytics\/gtmtips-10-useful-custom-javascript-tricks\/"},"modified":"2025-03-10T05:57:07","modified_gmt":"2025-03-10T05:57:07","slug":"gtmtips-10-useful-custom-javascript-tricks","status":"publish","type":"post","link":"https:\/\/fivemor.com\/?p=123584","title":{"rendered":"#GTMTips: 10 Useful Custom JavaScript Tricks"},"content":{"rendered":"<p> <br \/>\n<\/p>\n<div>\n<p>I recently published a <a href=\"https:\/\/www.simoahava.com\/categories\/gtm-tips\/\">#GTMTips<\/a> guide called <a href=\"https:\/\/www.simoahava.com\/gtm-tips\/10-useful-css-selectors\/\">10 Useful CSS Selectors<\/a>, and it was very well received. Inspired by the feedback, here\u2019s the next instalment. This time, we\u2019re going over some useful JavaScript tips and tricks that you can use to make your <a href=\"https:\/\/tagmanager.google.com\/\">Google Tag Manager<\/a> deployment even more efficient. <a href=\"https:\/\/www.simoahava.com\/tags\/javascript\/\">I\u2019ve written <strong>a lot<\/strong> about JavaScript in this blog<\/a>, and I intend to keep on doing so in the future. As always, if JavaScript is somewhat of a mystery to you, I strongly recommend you take the <a href=\"https:\/\/www.codecademy.com\/learn\/javascript\">Codecademy (free) course on JS<\/a>, and take a look at the other available web technology tracks while you\u2019re there!<\/p>\n<p>                <span class=\"simmer\"><br \/>\n  <span class=\"close\">X<\/span><\/p>\n<p>\n    <span class=\"fa fa-md fa-bell\"\/><br \/>\n    <strong>The Simmer Newsletter<\/strong>\n  <\/p>\n<p>\n    Subscribe to the <a href=\"https:\/\/www.simoahava.com\/newsletter\/\">Simmer newsletter<\/a> to get the latest news and content from Simo Ahava into your email inbox!\n  <\/p>\n<p>  <\/span><\/p>\n<h2 id=\"tip-54-10-useful-custom-javascript-tricks\">Tip 54: 10 Useful Custom JavaScript Tricks<\/h2>\n<div style=\"aspect-ratio: 960 \/ 540;\" class=\"figure nocaption\">\n<p>    <a href=\"https:\/\/www.simoahava.com\/images\/2017\/01\/10-useful-custom-javascript-tricks.jpg\" title=\"10 Useful Custom JavaScript Tricks\"><\/p>\n<p>    <img decoding=\"async\" class=\"fig-img\" height=\"540\" width=\"960\" loading=\"lazy\" src=\"https:\/\/www.simoahava.com\/images\/2017\/01\/10-useful-custom-javascript-tricks.jpg#ZgotmplZ\" alt=\"10 Useful Custom JavaScript Tricks\"\/><\/p>\n<p>    <\/a><\/p>\n<\/div>\n<p>You can deploy these tricks in Custom HTML Tags or Custom JavaScript Variables, since they are the only contexts within Google Tag Manager where you can execute arbitrary JavaScript. Note that some of the tricks are just code snippets, so you will need to understand enough of how <a href=\"https:\/\/www.simoahava.com\/analytics\/javascript-101-gtm-part-1\/\">Google Tag Manager and JavaScript mesh together<\/a> to be able to deploy them successfully.<\/p>\n<p>Before adding any of these to your deployments, remember to use <a href=\"http:\/\/caniuse.com\/\">caniuse.com<\/a> to check for browser compatibility, and the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\">MDN JavaScript Reference<\/a> to find alternative ways (AKA polyfills) for writing the unsupported methods.<\/p>\n<h2 id=\"1-string-methods\">1. String methods<\/h2>\n<p>String methods are utilities that you can use to modify any given string. Here are some of the most useful ones, in my opinion.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#aaa;font-style:italic\">\/\/ Use .trim() to strip leading and trailing whitespace from a string.\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#a50\">\"   Oh no! Leading AND trailing whitespace!!   \"<\/span>.trim();\n<span style=\"color:#aaa;font-style:italic\">\/\/ Result: \"Oh no! Leading AND trailing whitespace!!\" \n<\/span><span style=\"color:#aaa;font-style:italic\"\/>\n<span style=\"color:#aaa;font-style:italic\">\/\/ Use .replace() to replace characters or regular expressions with something else.\n<\/span><span style=\"color:#aaa;font-style:italic\">\/\/ .replace() without a regular expression replaces the first instance.\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#a50\">\"Food\"<\/span>.replace(<span style=\"color:#a50\">'o'<\/span>, <span style=\"color:#a50\">'e'<\/span>);\n<span style=\"color:#aaa;font-style:italic\">\/\/ Result: \"Feod\"\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#a50\">\"Food\"<\/span>.replace(<span style=\"color:#099\">\/o\/g<\/span>, <span style=\"color:#a50\">'e'<\/span>);\n<span style=\"color:#aaa;font-style:italic\">\/\/ Result: \"Feed\"\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>\n<span style=\"color:#aaa;font-style:italic\">\/\/ Use .toUpperCase() and .toLowerCase() to change the case of the entire string\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#a50\">\"MixED CaSe String\"<\/span>.toLowerCase();\n<span style=\"color:#aaa;font-style:italic\">\/\/ Result: \"mixed case string\"\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>\n<span style=\"color:#aaa;font-style:italic\">\/\/ Use .substring() to return only part of the string.\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#a50\">\"?some-query-key=some-query-value\"<\/span>.substring(<span style=\"color:#099\">1<\/span>);\n<span style=\"color:#aaa;font-style:italic\">\/\/ Returns: \"some-query-key=some-query-value\"\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#a50\">\"id: 12345-12345\"<\/span>.substring(<span style=\"color:#099\">4<\/span>,<span style=\"color:#099\">9<\/span>);\n<span style=\"color:#aaa;font-style:italic\">\/\/ Returns: \"12345\"\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>\n<span style=\"color:#aaa;font-style:italic\">\/\/ Use .split() to split the string into its constituents\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#a50\">\"get the second word of this sentence\"<\/span>.split(<span style=\"color:#a50\">' '<\/span>)[<span style=\"color:#099\">1<\/span>];\n<span style=\"color:#aaa;font-style:italic\">\/\/ Returns \"the\"\n<\/span><\/code><\/pre>\n<\/div>\n<p>Naturally, you can combine these in inventive ways. For example, to capitalize the first letter of any string you could do this:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">var<\/span> str = <span style=\"color:#a50\">\"capitalize the first letter of this string, please!\"<\/span>;\nstr = str.replace(<span style=\"color:#099\">\/^.\/<\/span>, str.substring(<span style=\"color:#099\">0<\/span>,<span style=\"color:#099\">1<\/span>).toUpperCase());\n<\/code><\/pre>\n<\/div>\n<p>Here we first identify the first letter of the string using a regular expression, after which we replace it with the first letter of the string that has been converted to upper case.<\/p>\n<h2 id=\"2-array-methods\">2. Array methods<\/h2>\n<p>Array methods are really powerful in any programming language. Mastering methods such as <code>filter()<\/code> and <code>forEach()<\/code> is critical if you want to make your JavaScript more compact and often more readable.<\/p>\n<h3 id=\"filter\">filter()<\/h3>\n<p><code>filter()<\/code> goes through each element in the Array, and returns a new Array for every element that passes the check you provide in the callback. Here\u2019s the syntax:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\">someArray.filter(<span style=\"color:#00a\">function<\/span>(eachItem) { \n  <span style=\"color:#00a\">return<\/span> eachItem === someCondition; \n});\n<\/code><\/pre>\n<\/div>\n<p>So <code>eachItem<\/code> is the variable where the iterator stores each member of the Array as it is processed. If the callback returns <code>true<\/code>, it means that the item is added to the returned, new Array. If it returns <code>false<\/code>, it\u2019s dropped.<\/p>\n<p>Here\u2019s an example:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#0aa\">window<\/span>.dataLayer = <span style=\"color:#0aa\">window<\/span>.dataLayer || [];\n<span style=\"color:#0aa\">window<\/span>.dataLayer.push({\n  <span style=\"color:#a50\">'event'<\/span> : <span style=\"color:#a50\">'addMe!'<\/span>\n},{\n  <span style=\"color:#a50\">'event'<\/span> : <span style=\"color:#a50\">'doNotAddMe!'<\/span>\n});\n\n<span style=\"color:#00a\">var<\/span> newArray = <span style=\"color:#0aa\">window<\/span>.dataLayer.filter(<span style=\"color:#00a\">function<\/span>(item) {\n  <span style=\"color:#00a\">return<\/span> item.event === <span style=\"color:#a50\">'addMe!'<\/span>;\n});\n<span style=\"color:#aaa;font-style:italic\">\/\/ Returns: [{'event' : 'addMe!'}]\n<\/span><\/code><\/pre>\n<\/div>\n<p>The iterator checks every single item for the property <code>event<\/code>, and returns <code>true<\/code> if that property has value <code>addMe!<\/code>. Thus the returned array only has those elements that have the key-value pair <code>\"event\" : \"addMe!\"<\/code>.<\/p>\n<h3 id=\"foreach\">forEach()<\/h3>\n<p>Remember the clumsy for-loop for iterating over an Array? Yuck! Instead, you can use the <code>forEach()<\/code> iterator.<\/p>\n<p><code>forEach()<\/code> receives each item in the array one-by-one, and you can then do whatever you wish with this item. The syntax is very simple and intuitive, and thus should be preferred over the confusing for-loop.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">var<\/span> array = [<span style=\"color:#a50\">\"I\"<\/span>, <span style=\"color:#099\">4<\/span>, <span style=\"color:#099\">2<\/span>, <span style=\"color:#00a\">true<\/span>, <span style=\"color:#a50\">\"love\"<\/span>, [<span style=\"color:#099\">1<\/span>,<span style=\"color:#099\">2<\/span>,<span style=\"color:#099\">3<\/span>], {chocolate: <span style=\"color:#a50\">'too'<\/span>}, <span style=\"color:#a50\">\"you\"<\/span>];\n<span style=\"color:#00a\">var<\/span> newArray = [];\n\narray.forEach(<span style=\"color:#00a\">function<\/span>(item) {\n  <span style=\"color:#00a\">if<\/span> (<span style=\"color:#00a\">typeof<\/span> item === <span style=\"color:#a50\">'string'<\/span>) {\n    newArray.push(item);\n  }\n});\n\nnewArray.join(<span style=\"color:#a50\">\" \"<\/span>);\n<span style=\"color:#aaa;font-style:italic\">\/\/ Result: \"I love you\"\n<\/span><\/code><\/pre>\n<\/div>\n<p>As you can see, it\u2019s more readable than a for-loop, as you don\u2019t have to access the original array in the iterator.<\/p>\n<h3 id=\"map\">map()<\/h3>\n<p>The <code>map()<\/code> iterates over each member in the array, again, but this time the code in the callback is executed against each member of the array, and a new array is returned with the results. Here\u2019s how to set it up:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\">array.map(<span style=\"color:#00a\">function<\/span>(item) {\n  <span style=\"color:#00a\">return<\/span> doSomething(item);\n});\n<\/code><\/pre>\n<\/div>\n<p>In other words, you are <em>mapping<\/em> each element in the array against the result of the callback function. Here\u2019s are some examples:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">var<\/span> array = [<span style=\"color:#099\">1<\/span>,<span style=\"color:#099\">2<\/span>,<span style=\"color:#099\">3<\/span>,<span style=\"color:#099\">4<\/span>,<span style=\"color:#099\">5<\/span>];\narray.map(<span style=\"color:#00a\">function<\/span>(item) {\n  <span style=\"color:#00a\">return<\/span> item * <span style=\"color:#099\">2<\/span>;\n});\n<span style=\"color:#aaa;font-style:italic\">\/\/ Result: [2,4,6,8,10]\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>\n<span style=\"color:#00a\">var<\/span> array = [<span style=\"color:#a50\">\"  please     \"<\/span>, <span style=\"color:#a50\">\"  trim\"<\/span>, <span style=\"color:#a50\">\"     us  \"<\/span>];\narray.map(<span style=\"color:#00a\">function<\/span>(item) {\n  <span style=\"color:#00a\">return<\/span> item.trim();\n});\n<span style=\"color:#aaa;font-style:italic\">\/\/ Result: [\"please\", \"trim\", \"us\"];\n<\/span><\/code><\/pre>\n<\/div>\n<h3 id=\"reduce\">reduce()<\/h3>\n<p>The <code>reduce()<\/code> method is often the most complex one, but it actually has a very simple principle: You provide the function with an accumulator, and each member of the array is then operated against this accumulator. You can also provide an initial value to the accumulator. Here\u2019s what the basic structure looks like:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\">array.reduce(<span style=\"color:#00a\">function<\/span>(accumulator, item) {\n  accumulator.doSomethingWith(item);\n  <span style=\"color:#00a\">return<\/span> accumulator;\n}, initialValue);\n<\/code><\/pre>\n<\/div>\n<p>This time, it\u2019s definitely easiest to learn via examples:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#aaa;font-style:italic\">\/\/ Example: calculate the sum of all even numbers in the array\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#00a\">var<\/span> array = [<span style=\"color:#099\">1<\/span>,<span style=\"color:#099\">6<\/span>,<span style=\"color:#099\">3<\/span>,<span style=\"color:#099\">4<\/span>,<span style=\"color:#099\">12<\/span>,<span style=\"color:#099\">17<\/span>,<span style=\"color:#099\">21<\/span>,<span style=\"color:#099\">27<\/span>,<span style=\"color:#099\">30<\/span>];\narray.reduce(<span style=\"color:#00a\">function<\/span>(accumulator, item) { \n  <span style=\"color:#00a\">if<\/span> (item % <span style=\"color:#099\">2<\/span> === <span style=\"color:#099\">0<\/span>) { \n    accumulator += item; \n  }\n  <span style=\"color:#00a\">return<\/span> accumulator; \n}, <span style=\"color:#099\">0<\/span>);\n<span style=\"color:#aaa;font-style:italic\">\/\/ Returns: 52\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>\n<span style=\"color:#aaa;font-style:italic\">\/\/ Example, concatenate a string of all product IDs in array\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#00a\">var<\/span> array = [{\n  <span style=\"color:#a50\">\"id\"<\/span> : <span style=\"color:#a50\">\"firstId\"<\/span>,\n  <span style=\"color:#a50\">\"name\"<\/span> : <span style=\"color:#a50\">\"T-shirts\"<\/span>\n},{\n  <span style=\"color:#a50\">\"id\"<\/span> : <span style=\"color:#a50\">\"secondId\"<\/span>,\n  <span style=\"color:#a50\">\"name\"<\/span> : <span style=\"color:#a50\">\"Pants\"<\/span>\n},{\n  <span style=\"color:#a50\">\"id\"<\/span> : <span style=\"color:#a50\">\"thirdId\"<\/span>,\n  <span style=\"color:#a50\">\"name\"<\/span> : <span style=\"color:#a50\">\"shoes\"<\/span>\n}];\narray.reduce(<span style=\"color:#00a\">function<\/span>(accumulator, item) {\n  accumulator.push(item.id);\n  <span style=\"color:#00a\">return<\/span> accumulator;\n},\u00a0[]).join();\n<span style=\"color:#aaa;font-style:italic\">\/\/ Returns: \"firstId,secondId,thirdId\"\n<\/span><\/code><\/pre>\n<\/div>\n<h2 id=\"3-ternary-operator\">3. Ternary operator<\/h2>\n<p>The ternary operator is just a very simple shorthand for running conditional checks in JavaScript. Here\u2019s an example:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#aaa;font-style:italic\">\/\/ BEFORE:\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#00a\">if<\/span> (something) {\n  somethingElse();\n} <span style=\"color:#00a\">else<\/span> {\n  somethingDifferent();\n}\n\n<span style=\"color:#aaa;font-style:italic\">\/\/ AFTER:\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>something ? somethingElse() : somethingDifferent();\n<\/code><\/pre>\n<\/div>\n<p>The ternary operator is thus used to combine an if-statement into a simple expression. First you provide an expression that evaluates to a <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Glossary\/Truthy\">truthy<\/a> or <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Glossary\/Falsy\">falsy<\/a> value, such as <code>me.name() === \"Simo\"<\/code>. Then you type the question mark, after which you write an expression that is executed if the first item evaluates to a <em>truthy<\/em> value. Finally, you type the colon <code>:<\/code>, after which you type the expression that is executed if the first item evaluates to a <em>falsy<\/em> value.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#aaa;font-style:italic\">\/\/ BEFORE:\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#00a\">if<\/span> (<span style=\"color:#0aa\">document<\/span>.querySelector(<span style=\"color:#a50\">'#findThisId'<\/span>) !== <span style=\"color:#00a\">null<\/span>) {\n  <span style=\"color:#00a\">return<\/span> <span style=\"color:#0aa\">document<\/span>.querySelector(<span style=\"color:#a50\">'#findThisId'<\/span>);\n} <span style=\"color:#00a\">else<\/span> {\n  <span style=\"color:#00a\">return<\/span> <span style=\"color:#a50\">\"Not found!\"<\/span>;\n}\n\n<span style=\"color:#aaa;font-style:italic\">\/\/ AFTER:\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#00a\">return<\/span> <span style=\"color:#0aa\">document<\/span>.querySelector(<span style=\"color:#a50\">'#findThisId'<\/span>) ? <span style=\"color:#0aa\">document<\/span>.querySelector(<span style=\"color:#a50\">'#findThisId'<\/span>) : <span style=\"color:#a50\">\"Not found!\"<\/span>;\n\n<span style=\"color:#aaa;font-style:italic\">\/\/ EVEN BETTER:\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#00a\">return<\/span> <span style=\"color:#0aa\">document<\/span>.querySelector(<span style=\"color:#a50\">'#findThisId'<\/span>) || <span style=\"color:#a50\">\"Not found!\"<\/span>;\n<\/code><\/pre>\n<\/div>\n<p>As you can see, sometimes there are even more efficient ways to process JavaScript statements than the ternary operator. Especially when working with simple binary checks (if value exists, return it), it might be better to just use basic <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Operators\/Logical_Operators\">logical operators<\/a> instead of complex statements or expressions.<\/p>\n<h2 id=\"4-return-click-urlindexofpage-hostname---1\">4. return {{Click URL}}.indexOf({{Page Hostname}}) &gt; -1<\/h2>\n<p>This is very Google Tag Managerish. It\u2019s a simple Custom JavaScript Variable that returns <code>true<\/code> if the clicked element URL contains the current page hostname, and <code>false<\/code> otherwise. In other words, it returns <code>true<\/code> if the clicked link is internal, and <code>false<\/code> if it takes the user away from the website.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">function<\/span>() {\n  <span style=\"color:#00a\">return<\/span> {{Click URL}}.indexOf({{Page Hostname}}) &gt; -<span style=\"color:#099\">1<\/span>;\n}\n<\/code><\/pre>\n<\/div>\n<h2 id=\"5-return-click-urlsplitpop\">5. return {{Click URL}}.split(&#8216;\/&#8217;).pop()<\/h2>\n<p>Again, a simple Custom JavaScript Variable. This is especially useful when tracking <a href=\"https:\/\/www.simoahava.com\/gtm-tips\/track-file-downloads-in-gtm-v2\/\">file downloads<\/a>, as it returns the actual filename of the downloaded item. It does this by returning whatever is in the clicked URL after the last \u2018\/\u2019.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">function<\/span>() {\n  <span style=\"color:#aaa;font-style:italic\">\/\/ Example: https:\/\/www.simoahava.com\/downloads\/download_me.pdf\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>  <span style=\"color:#00a\">return<\/span> {{Click URL}}.split(<span style=\"color:#a50\">'\/'<\/span>).pop();\n  <span style=\"color:#aaa;font-style:italic\">\/\/ Returns: download_me.pdf\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>}\n<\/code><\/pre>\n<\/div>\n<h2 id=\"6-create-a-random-unique-guid\">6. Create a random, unique GUID<\/h2>\n<p>Every now and then it\u2019s useful to create a random ID in GTM. For example, if you want to measure <a href=\"https:\/\/www.simoahava.com\/analytics\/improve-data-collection-with-four-custom-dimensions\/\">session IDs<\/a>, or if you want to assign a unique identifier to each page hit, you can achieve this with the following Custom JavaScript Variable.<\/p>\n<p>The variable creates a GUID string (\u201cGlobally Unique Identifier\u201d), and even though uniqueness isn\u2019t guaranteed, it\u2019s still very likely. There\u2019s only a microscopically small chance of collision.<\/p>\n<p>This solution is gratefully adapted from <a href=\"http:\/\/stackoverflow.com\/questions\/105034\/create-guid-uuid-in-javascript\/2117523#2117523\">this StackOverflow post<\/a>.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">function<\/span>() {\n  <span style=\"color:#00a\">return<\/span> <span style=\"color:#a50\">'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'<\/span>.replace(<span style=\"color:#099\">\/[xy]\/g<\/span>, <span style=\"color:#00a\">function<\/span>(c) {\n    <span style=\"color:#00a\">var<\/span> r = <span style=\"color:#0aa\">Math<\/span>.random()*<span style=\"color:#099\">16<\/span>|<span style=\"color:#099\">0<\/span>, v = c == <span style=\"color:#a50\">'x'<\/span> ? r : (r&amp;<span style=\"color:#099\">0x3<\/span>|<span style=\"color:#099\">0x8<\/span>);\n    <span style=\"color:#00a\">return<\/span> v.toString(<span style=\"color:#099\">16<\/span>);\n  });\n}\n<\/code><\/pre>\n<\/div>\n<h2 id=\"7-return-an-iso-formatted-timestamp\">7. Return an ISO-formatted timestamp<\/h2>\n<p>This is one of my favorite solutions, as it lets you convert the current client time to a proper, readable timestamp. In addition, it has the timezone offset included, so you\u2019ll know just how much the users\u2019 local times differ from your own timezone. I send this to Google Analytics with <a href=\"https:\/\/www.simoahava.com\/analytics\/improve-data-collection-with-four-custom-dimensions\/\">every single hit<\/a>, so that I can create a timeline of events when analyzing the data.<\/p>\n<p>This solution is gratefully adapted from <a href=\"http:\/\/stackoverflow.com\/a\/17415677\">this StackOverflow post<\/a>.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">function<\/span>() {\n  <span style=\"color:#00a\">var<\/span> now = <span style=\"color:#00a\">new<\/span> <span style=\"color:#0aa\">Date<\/span>();\n  <span style=\"color:#00a\">var<\/span> tzo = -now.getTimezoneOffset();\n  <span style=\"color:#00a\">var<\/span> dif = tzo &gt;= <span style=\"color:#099\">0<\/span> ? <span style=\"color:#a50\">'+'<\/span> : <span style=\"color:#a50\">'-'<\/span>;\n  <span style=\"color:#00a\">var<\/span> pad = <span style=\"color:#00a\">function<\/span>(num) {\n    <span style=\"color:#00a\">var<\/span> norm = <span style=\"color:#0aa\">Math<\/span>.abs(<span style=\"color:#0aa\">Math<\/span>.floor(num));     \n    <span style=\"color:#00a\">return<\/span> (norm 10 ? <span style=\"color:#a50\">'0'<\/span> : <span style=\"color:#a50\">''<\/span>) + norm;\n  };\n  <span style=\"color:#00a\">return<\/span> now.getFullYear() \n    + <span style=\"color:#a50\">'-'<\/span> + pad(now.getMonth()+<span style=\"color:#099\">1<\/span>)\n    + <span style=\"color:#a50\">'-'<\/span> + pad(now.getDate())\n    + <span style=\"color:#a50\">'T'<\/span> + pad(now.getHours())\n    + <span style=\"color:#a50\">':'<\/span> + pad(now.getMinutes()) \n    + <span style=\"color:#a50\">':'<\/span> + pad(now.getSeconds())\n    + <span style=\"color:#a50\">'.'<\/span> + pad(now.getMilliseconds())\n    + dif + pad(tzo \/ <span style=\"color:#099\">60<\/span>) \n    + <span style=\"color:#a50\">':'<\/span> + pad(tzo % <span style=\"color:#099\">60<\/span>);\n  <span style=\"color:#aaa;font-style:italic\">\/\/ Returns, for example: 2017-01-18T11:58:32.977+02:00\n<\/span><span style=\"color:#aaa;font-style:italic\"\/>}\n<\/code><\/pre>\n<\/div>\n<h2 id=\"8-matches-polyfill\">8. .matches() polyfill<\/h2>\n<p>When working with the Document Object Model (DOM), being able to identify elements is crucial. We already have a bunch of wonderful <a href=\"https:\/\/www.simoahava.com\/gtm-tips\/10-useful-css-selectors\/\">CSS selectors<\/a> at our disposal, but now we just need a method we can use to check if any given element matches one of these selectors.<\/p>\n<p>Well, there\u2019s the <code>Element.matches(someSelector)<\/code> method that you can use, but it doesn\u2019t have <a href=\"http:\/\/caniuse.com\/#search=matches\">stellar browser support, even with prefixes<\/a>. With this solution, you can always use <code>.matches()<\/code> without having to worry about browser support. This trick is called a <strong>polyfill<\/strong>, as it patches lack of feature support with a workaround using JavaScript that is universally supported.<\/p>\n<p>First, here\u2019s how the method works in general:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#aaa;font-style:italic\">\/\/ Check if the parent of the clicked element has ID #testMe\n<\/span><span style=\"color:#aaa;font-style:italic\"\/><span style=\"color:#00a\">var<\/span> el = {{Click Element}};\nconsole.log(el.parentElement.matches(<span style=\"color:#a50\">'#testMe'<\/span>));\n<span style=\"color:#aaa;font-style:italic\">\/\/ RESULT: true or false, depending on if the parent element matches the selector.\n<\/span><\/code><\/pre>\n<\/div>\n<p>To implement <a href=\"https:\/\/developer.mozilla.org\/en\/docs\/Web\/API\/Element\/matches#Polyfill\">the polyfill<\/a>, either ask your developers to add it to the site JavaScript as early as possible in the page load sequence, or use Google Tag Manager.<\/p>\n<p>In Google Tag Manager, you\u2019ll need a Custom HTML Tag that fires as early as possible in the container load sequence (i.e. All Pages trigger with a high tag priority).<\/p>\n<p>Here\u2019s the code you need to add to the Custom HTML Tag. It\u2019s gratefully adapted from <a href=\"https:\/\/developer.mozilla.org\/en\/docs\/Web\/API\/Element\/matches#Polyfill\">this MDN reference page<\/a>.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-html\" data-lang=\"html\">script&gt;\n  <span style=\"color:#00a\">if<\/span> (!Element.prototype.matches) {\n    Element.prototype.matches = \n      Element.prototype.matchesSelector || \n      Element.prototype.mozMatchesSelector ||\n      Element.prototype.msMatchesSelector || \n      Element.prototype.oMatchesSelector || \n      Element.prototype.webkitMatchesSelector ||\n      <span style=\"color:#00a\">function<\/span>(s) {\n        <span style=\"color:#00a\">var<\/span> matches = (<span style=\"color:#00a\">this<\/span>.<span style=\"color:#0aa\">document<\/span> || <span style=\"color:#00a\">this<\/span>.ownerDocument).querySelectorAll(s),\n            i = matches.length;\n        <span style=\"color:#00a\">while<\/span> (--i &gt;= <span style=\"color:#099\">0<\/span> &amp;&amp; matches.item(i) !== <span style=\"color:#00a\">this<\/span>) {}\n        <span style=\"color:#00a\">return<\/span> i &gt; -<span style=\"color:#099\">1<\/span>;            \n      };\n  }\n<span style=\"color:#1e90ff;font-weight:bold\">script<\/span>&gt;<\/code><\/pre>\n<\/div>\n<p>The polyfill modifies the actual prototype of the <code>Element<\/code> object, which all HTML and DOM elements inherit from. After modifying the prototype, you can use the <code>matches()<\/code> method with confidence in all your GTM and site JavaScript.<\/p>\n<h2 id=\"9-dom-traversal\">9. DOM traversal<\/h2>\n<p>Sometimes it\u2019s necessary to climb up (or down) the Document Object Model. For example, if you\u2019re using a <a href=\"https:\/\/support.google.com\/tagmanager\/answer\/6106961?hl=en#Click\">Click \/ All Elements trigger<\/a>, it always targets the actual element that was clicked. But that\u2019s not always necessarily the element you want to track! Say you have an HTML structure like this:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-html\" data-lang=\"html\">a <span style=\"color:#1e90ff\">href<\/span>=<span style=\"color:#a50\">\"takemeaway.html\"<\/span>&gt;\n  button <span style=\"color:#1e90ff\">id<\/span>=<span style=\"color:#a50\">\"clickMe\"<\/span>&gt;\n    span&gt;Click Me!<span style=\"color:#1e90ff;font-weight:bold\">span<\/span>&gt;\n  <span style=\"color:#1e90ff;font-weight:bold\">button<\/span>&gt;\n<span style=\"color:#1e90ff;font-weight:bold\">a<\/span>&gt;<\/code><\/pre>\n<\/div>\n<p>Now, if you use a Click \/ All Elements trigger, the element that is captured in the click is the <code><span\/><\/code>. But I\u2019m guessing you actually want to use the <code><a href=\"&quot;takemeaway.html&quot;\"\/><\/code> element, since you\u2019re more interested in knowing what happens <em>after<\/em> the click. So, you can use this Custom JavaScript Variable to return the nearest link above the clicked element in the DOM tree:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">function<\/span>() {\n  <span style=\"color:#00a\">var<\/span> el = {{Click Element}};\n  <span style=\"color:#00a\">while<\/span> (!el.matches(<span style=\"color:#a50\">'a'<\/span>) &amp;&amp; !el.matches(<span style=\"color:#a50\">'body'<\/span>)) {\n    el = el.parentElement;\n  }\n  <span style=\"color:#00a\">return<\/span> el.matches(<span style=\"color:#a50\">'a'<\/span>) ? el : <span style=\"color:#00a\">undefined<\/span>;\n}\n<\/code><\/pre>\n<\/div>\n<p>NOTE! This relies on the <code>matches()<\/code> method, so don\u2019t forget to implement the polyfill from above, first!<\/p>\n<p>This Custom JavaScript Variable climbs up the DOM until it reaches the first link element it finds (<code>'a'<\/code>), after which it returns this element. If it doesn\u2019t find a link, it returns <code>undefined<\/code> instead.<\/p>\n<h2 id=\"10-set-browser-cookies-with-ease\">10. Set browser cookies with ease<\/h2>\n<p>Cookies are a great, if somewhat outdated, way of <a href=\"https:\/\/www.simoahava.com\/analytics\/two-ways-to-persist-data-via-google-tag-manager\/\">storing information in the browser<\/a>. Since Google Tag Manager operates in the context of a web page, it is essentially stateless. Thus any information you want to persist from one page to another must be stored either in the server or the browser itself. The latter is far easier to do, and with browser cookies it\u2019s just a question of adding a couple of lines of code to your GTM deployment.<\/p>\n<p>First, you need a Custom JavaScript Variable. You can name it <strong>{{Set Cookie}}<\/strong>, for example.<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\"><span style=\"color:#00a\">function<\/span>() {\n  <span style=\"color:#00a\">return<\/span> <span style=\"color:#00a\">function<\/span>(name, value, ms, path, domain) {\n    <span style=\"color:#00a\">if<\/span> (!name || !value) {\n      <span style=\"color:#00a\">return<\/span>;\n    }\n    <span style=\"color:#00a\">var<\/span> d;\n    <span style=\"color:#00a\">var<\/span> cpath = path ? <span style=\"color:#a50\">'; path='<\/span> + path : <span style=\"color:#a50\">''<\/span>;\n    <span style=\"color:#00a\">var<\/span> cdomain = domain ? <span style=\"color:#a50\">'; domain='<\/span> + domain : <span style=\"color:#a50\">''<\/span>;\n    <span style=\"color:#00a\">var<\/span> expires = <span style=\"color:#a50\">''<\/span>;\n    <span style=\"color:#00a\">if<\/span> (ms) {\n      d = <span style=\"color:#00a\">new<\/span> <span style=\"color:#0aa\">Date<\/span>();\n      d.setTime(d.getTime() + ms);\n      expires = <span style=\"color:#a50\">'; expires='<\/span> + d.toUTCString();\n    }\n    <span style=\"color:#0aa\">document<\/span>.cookie = name + <span style=\"color:#a50\">\"=\"<\/span> + value + expires + cpath + cdomain;\n  }\n}\n<\/code><\/pre>\n<\/div>\n<p>This Custom JavaScript Variable returns a function that takes five parameters:<\/p>\n<ul>\n<li>\n<p><strong>name<\/strong> (required): the name of the cookie (string)<\/p>\n<\/li>\n<li>\n<p><strong>value<\/strong> (required): the value of the cookie (string)<\/p>\n<\/li>\n<li>\n<p><strong>ms<\/strong>: expiration time of the cookie in milliseconds. If unset, defaults to a Session cookie (expires when the browser is closed).<\/p>\n<\/li>\n<li>\n<p><strong>path<\/strong>: the path of the cookie. If unset, defaults to the current page path.<\/p>\n<\/li>\n<li>\n<p><strong>domain<\/strong>: the domain of the cookie. If unset, defaults to the current domain.<\/p>\n<\/li>\n<\/ul>\n<p>To use the cookie, you invoke it with:<\/p>\n<div class=\"highlight\">\n<pre style=\"background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4\"><code class=\"language-javascript\" data-lang=\"javascript\">{{Set Cookie}}(<span style=\"color:#a50\">'test'<\/span>, <span style=\"color:#a50\">'true'<\/span>, <span style=\"color:#099\">10000<\/span>, <span style=\"color:#a50\">'\/'<\/span>, <span style=\"color:#a50\">'simoahava.com'<\/span>);\n<\/code><\/pre>\n<\/div>\n<p>The code above, when run in GTM, sets a cookie with name <code>\"test\"<\/code>, value <code>\"true\"<\/code>, expiration time of ten seconds, and it\u2019s set on the root of the <code>simoahava.com<\/code> domain.<\/p>\n<p>With this helper, setting cookies is a breeze. Remember that you can then use the handy <a href=\"https:\/\/www.simoahava.com\/analytics\/variable-guide-google-tag-manager\/\">1st Party Cookie<\/a> variable in GTM to retrieve values from set cookies.<\/p>\n<h2 id=\"summary\">Summary<\/h2>\n<p>Here I listed 10 JavaScript tricks that I use (almost) all the time. There\u2019s plenty more to JavaScript, but with these methods you can get started on making your clunky Google Tag Manager deployment a thing of the past.<\/p>\n<p>Do you have any favorite methods, tips, or tricks you want to share? Please do so in the comments below.<\/p>\n<\/p><\/div>\n\n","protected":false},"excerpt":{"rendered":"<p>I recently published a #GTMTips guide called 10 Useful CSS Selectors, and it was very well received. Inspired by the feedback, here\u2019s the next instalment. This time, we\u2019re going over some useful JavaScript tips and tricks that you can use to make your Google Tag Manager deployment even more efficient. I\u2019ve written a lot about [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":123585,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12033],"tags":[834,14492,29091,660],"dealstore":[],"offerexpiration":[],"class_list":["post-123584","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-analytics","tag-custom","tag-gtmtips","tag-javascript","tag-tricks"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>#GTMTips: 10 Useful Custom JavaScript Tricks - Som2ny Network<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/fivemor.com\/?p=123584\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"#GTMTips: 10 Useful Custom JavaScript Tricks - Som2ny Network\" \/>\n<meta property=\"og:description\" content=\"I recently published a #GTMTips guide called 10 Useful CSS Selectors, and it was very well received. Inspired by the feedback, here\u2019s the next instalment. This time, we\u2019re going over some useful JavaScript tips and tricks that you can use to make your Google Tag Manager deployment even more efficient. I\u2019ve written a lot about [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/fivemor.com\/?p=123584\" \/>\n<meta property=\"og:site_name\" content=\"Som2ny Network\" \/>\n<meta property=\"article:published_time\" content=\"2025-03-10T05:57:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"960\" \/>\n\t<meta property=\"og:image:height\" content=\"540\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"admin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"12 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/fivemor.com\/?p=123584#article\",\"isPartOf\":{\"@id\":\"https:\/\/fivemor.com\/?p=123584\"},\"author\":{\"name\":\"admin\",\"@id\":\"https:\/\/fivemor.com\/#\/schema\/person\/b85e3c3dc0e1daea076524dc8810c371\"},\"headline\":\"#GTMTips: 10 Useful Custom JavaScript Tricks\",\"datePublished\":\"2025-03-10T05:57:07+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/fivemor.com\/?p=123584\"},\"wordCount\":1772,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/fivemor.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/fivemor.com\/?p=123584#primaryimage\"},\"thumbnailUrl\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg\",\"keywords\":[\"Custom\",\"GTMTips\",\"JavaScript\",\"Tricks\"],\"articleSection\":[\"Analytics\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/fivemor.com\/?p=123584#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/fivemor.com\/?p=123584\",\"url\":\"https:\/\/fivemor.com\/?p=123584\",\"name\":\"#GTMTips: 10 Useful Custom JavaScript Tricks - Som2ny Network\",\"isPartOf\":{\"@id\":\"https:\/\/fivemor.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/fivemor.com\/?p=123584#primaryimage\"},\"image\":{\"@id\":\"https:\/\/fivemor.com\/?p=123584#primaryimage\"},\"thumbnailUrl\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg\",\"datePublished\":\"2025-03-10T05:57:07+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/fivemor.com\/?p=123584#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/fivemor.com\/?p=123584\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/fivemor.com\/?p=123584#primaryimage\",\"url\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg\",\"contentUrl\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg\",\"width\":960,\"height\":540},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/fivemor.com\/?p=123584#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/fivemor.com\/?bp_activities=1\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"#GTMTips: 10 Useful Custom JavaScript Tricks\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/fivemor.com\/#website\",\"url\":\"https:\/\/fivemor.com\/\",\"name\":\"Som2ny Network\",\"description\":\"Daily Deals\",\"publisher\":{\"@id\":\"https:\/\/fivemor.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/fivemor.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/fivemor.com\/#organization\",\"name\":\"Som2ny Network\",\"url\":\"https:\/\/fivemor.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/fivemor.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png\",\"contentUrl\":\"https:\/\/fivemor.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png\",\"width\":300,\"height\":86,\"caption\":\"Som2ny Network\"},\"image\":{\"@id\":\"https:\/\/fivemor.com\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/fivemor.com\/#\/schema\/person\/b85e3c3dc0e1daea076524dc8810c371\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/fivemor.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Ffivemor.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Ffivemor.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png\",\"caption\":\"admin\"},\"sameAs\":[\"https:\/\/fivemor.com\"],\"url\":\"https:\/\/fivemor.com\/?author=1\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"#GTMTips: 10 Useful Custom JavaScript Tricks - Som2ny Network","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/fivemor.com\/?p=123584","og_locale":"en_US","og_type":"article","og_title":"#GTMTips: 10 Useful Custom JavaScript Tricks - Som2ny Network","og_description":"I recently published a #GTMTips guide called 10 Useful CSS Selectors, and it was very well received. Inspired by the feedback, here\u2019s the next instalment. This time, we\u2019re going over some useful JavaScript tips and tricks that you can use to make your Google Tag Manager deployment even more efficient. I\u2019ve written a lot about [&hellip;]","og_url":"https:\/\/fivemor.com\/?p=123584","og_site_name":"Som2ny Network","article_published_time":"2025-03-10T05:57:07+00:00","og_image":[{"width":960,"height":540,"url":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg","type":"image\/jpeg"}],"author":"admin","twitter_card":"summary_large_image","twitter_misc":{"Written by":"admin","Est. reading time":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/fivemor.com\/?p=123584#article","isPartOf":{"@id":"https:\/\/fivemor.com\/?p=123584"},"author":{"name":"admin","@id":"https:\/\/fivemor.com\/#\/schema\/person\/b85e3c3dc0e1daea076524dc8810c371"},"headline":"#GTMTips: 10 Useful Custom JavaScript Tricks","datePublished":"2025-03-10T05:57:07+00:00","mainEntityOfPage":{"@id":"https:\/\/fivemor.com\/?p=123584"},"wordCount":1772,"commentCount":0,"publisher":{"@id":"https:\/\/fivemor.com\/#organization"},"image":{"@id":"https:\/\/fivemor.com\/?p=123584#primaryimage"},"thumbnailUrl":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg","keywords":["Custom","GTMTips","JavaScript","Tricks"],"articleSection":["Analytics"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/fivemor.com\/?p=123584#respond"]}]},{"@type":"WebPage","@id":"https:\/\/fivemor.com\/?p=123584","url":"https:\/\/fivemor.com\/?p=123584","name":"#GTMTips: 10 Useful Custom JavaScript Tricks - Som2ny Network","isPartOf":{"@id":"https:\/\/fivemor.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/fivemor.com\/?p=123584#primaryimage"},"image":{"@id":"https:\/\/fivemor.com\/?p=123584#primaryimage"},"thumbnailUrl":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg","datePublished":"2025-03-10T05:57:07+00:00","breadcrumb":{"@id":"https:\/\/fivemor.com\/?p=123584#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/fivemor.com\/?p=123584"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/fivemor.com\/?p=123584#primaryimage","url":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg","contentUrl":"https:\/\/fivemor.com\/wp-content\/uploads\/2025\/03\/10-useful-custom-javascript-tricks.jpg","width":960,"height":540},{"@type":"BreadcrumbList","@id":"https:\/\/fivemor.com\/?p=123584#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/fivemor.com\/?bp_activities=1"},{"@type":"ListItem","position":2,"name":"#GTMTips: 10 Useful Custom JavaScript Tricks"}]},{"@type":"WebSite","@id":"https:\/\/fivemor.com\/#website","url":"https:\/\/fivemor.com\/","name":"Som2ny Network","description":"Daily Deals","publisher":{"@id":"https:\/\/fivemor.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/fivemor.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/fivemor.com\/#organization","name":"Som2ny Network","url":"https:\/\/fivemor.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/fivemor.com\/#\/schema\/logo\/image\/","url":"https:\/\/fivemor.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png","contentUrl":"https:\/\/fivemor.com\/wp-content\/uploads\/2026\/07\/4a0953c4-logo-300x86-1.png","width":300,"height":86,"caption":"Som2ny Network"},"image":{"@id":"https:\/\/fivemor.com\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/fivemor.com\/#\/schema\/person\/b85e3c3dc0e1daea076524dc8810c371","name":"admin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/fivemor.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Ffivemor.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/729ae85bf62b9917e93538db2f2688ca?s=96&r=g&default=https%3A%2F%2Ffivemor.com%2Fwp-content%2Fplugins%2Fbuddypress-first-letter-avatar%2Fimages%2Fdefault%2F96%2Flatin_a.png","caption":"admin"},"sameAs":["https:\/\/fivemor.com"],"url":"https:\/\/fivemor.com\/?author=1"}]}},"_links":{"self":[{"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/posts\/123584","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=123584"}],"version-history":[{"count":0,"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/posts\/123584\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=\/wp\/v2\/media\/123585"}],"wp:attachment":[{"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=123584"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=123584"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=123584"},{"taxonomy":"dealstore","embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fdealstore&post=123584"},{"taxonomy":"offerexpiration","embeddable":true,"href":"https:\/\/fivemor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fofferexpiration&post=123584"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}