<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jevgenijs Kazanins on Medium]]></title>
        <description><![CDATA[Stories by Jevgenijs Kazanins on Medium]]></description>
        <link>https://medium.com/@jev?source=rss-8e7b507d5346------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b8mUgQz8ZnTlKG65t6h8dQ.jpeg</url>
            <title>Stories by Jevgenijs Kazanins on Medium</title>
            <link>https://medium.com/@jev?source=rss-8e7b507d5346------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:17:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Use Query Explorer to Get Any Data Out of Google Analytics]]></title>
            <link>https://medium.com/@jev/how-to-use-query-explorer-to-get-any-data-out-of-google-analytics-62ae3ed74667?source=rss-8e7b507d5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/62ae3ed74667</guid>
            <dc:creator><![CDATA[Jevgenijs Kazanins]]></dc:creator>
            <pubDate>Thu, 25 Dec 2014 07:46:33 GMT</pubDate>
            <atom:updated>2014-12-25T07:46:33.362Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is Query Explorer?</h4><p>You have probably encountered situations in which <strong>Google Analytics interface didn’t allow you to get the data in the dimensions you wanted to</strong>. The easiest example would be: try getting the percentage of website visitors by Operating System -&gt; Browser -&gt; Browser Version in a single view in Google Analytics (quite a frequent request from QA teams, isn’t it?).</p><p>Most likely, you will end up using a Custom Report, but you will still hit a wall, as <strong>Google Analytics interface isn’t designed to present the data sliced by more than 2 dimensions</strong> (i.e. getting the number of users by Operating System -&gt; Browser is easy), and that’s why Google created <a href="https://developers.google.com/analytics/devguides/reporting/">Reporting API</a>. Not happy with the limitations of the UI? Just use the API.</p><p>API is all fun and games for engineers, but for regular mortals, like us, the marketing folks, Google created Query Explorer.<strong> Elevator pitch for Query Explorer would be “explore the power of Google Analytics Reporting API without writing a single line of code”.</strong></p><p>If you are an advanced user of Google Analytics (and not an engineer), then I suggest you start with visiting and bookmarking the <a href="https://ga-dev-tools.appspot.com/explorer/">Query Explorer page</a>, and for those who don’t trust clicking links, here is screenshot of Query Explorer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*WG8zkyUNrqzIe1FXnEeJZQ.png" /></figure><blockquote><strong>If you’re on Mac, use Chrome of Firefox, as there is no “Get Data” button if you’re using Safari. Not sure if this is by design, but the most important button is just not there for Safari users.</strong></blockquote><p>I’ll explain each field in more details below, but for now, in order to get the data out of Google Analytics, you need to do two things:</p><ul><li><strong>Select the correct Google Analytics View</strong> that contains the data;</li><li><strong>Formulate a data query</strong> using several fields, such as dimensions, metrics, filtes, etc.</li></ul><p>If you’re successful with the above, you will get the data out in a form of a table and a link to a .TSV file (don’t worry, it’s almost the same as CSV, which stands for Comma Separated Values, just that the values in a TSV file are separated by TABs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkweUMaZxZ3srbdoLvSc2g.png" /></figure><h4>Selecting Google Analytics View</h4><p>This part is really straightforward: if you are logged in, then the list of Google Analytics Accounts, Properties and Views will be automatically populated. Therefore, everything you have to do is to select, using drop downs, the correct Google Analytics view that contains the data you want to get.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*2JoTOwnAF6tZYGwlzYZgHg.png" /></figure><p>If you have selected one of the Views, the field “ids” (not sure why the use of plural) will be autocomplete with this view’s ID.</p><h4>Formulating Queries</h4><p>Formulating a query boils down to telling Query Explorer which <strong>metrics </strong>you want to get, sliced by which <strong>dimensions</strong>, in which <strong>date range. </strong>You can also get the data for a specific <strong>segment </strong>of users, as well as apply <strong>filters </strong>and <strong>sorting</strong>.</p><p><strong>Dimensions and Metrics<br></strong>If you have never worked with Google Analytics Reporting API, the concept of dimensions and metrics might be confusing at first. Let me use a screenshot from Google Analytics to explain the concept:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*EkM3rslrJ6oz4yz48RM7Sw.jpeg" /></figure><p>The above image shows standard Acquisition -&gt; Channels report from Google Analytics. In this case the <strong>dimensions </strong>are Default Channel Grouping, and the <strong>metrics </strong>are Sessions, News Sessions, New Users, etc. Let’s take another example, Acquisition -&gt; All traffic report:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*ZrDvp6aDxX9LYw0K8V8p6w.jpeg" /></figure><p>In the above example, <strong>dimensions </strong>are Source/Medium, while the <strong>metrics </strong>are Sessions, New Sessions, New Users, etc.</p><p>Once you are comfortable with the difference between dimensions and metrics, you can formulate a query for Query Explorer. A nice thing about Query Explorer is that it provides a detailed explanation of the each dimension and metric once you hover over it in the drop down menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QV_1zUkfQcT13lUkQw-ujA.png" /></figure><p>Similarly to dimensions, hovering over a specific metrics in the drop down menu gives you an explanation of it meaning, i.e. in the example below the metric <strong>ga:adClicks</strong> is explained, as “the total number of times users have licked on an ad to reach your property”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*sc_BYZOGXGRM37as_Nyu6A.png" /></figure><p><strong>You can specify multiple dimensions or metrics using a comma as a separator (although there is a limit of 7 dimensions and 10 metrics)</strong>, and I am pretty sure that over time you’ll lean their names by heart (just don’t forget that all dimensions and metrics start with “ga:”).</p><p><strong>Segments<br></strong>Similarly to the regular Google Analytics interface<strong> you can query the data for a specific segment (i.e. “Mobile Traffic”)</strong>. If you expand the drop down, you will see a list of both “Default Segments” and the “Custom Segments” that you have defined. Apparetly, it is possible to formulate a custom segment right in the Query Explorer, but honestly, I never had a need for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bu4Uy-HM8_0BOILp9Xd0pw.png" /></figure><p><strong>Filters and Sorting<br></strong>You can filter the resulting data using one or several dimensions as filters. For instance, the below will show filter for ogranic Google traffic:</p><blockquote><strong>ga:sourceMedium==google / organic</strong></blockquote><p>and the following will show organic OR paid traffic from Google:</p><blockquote><strong>ga:sourceMedium==google / organic,ga:sourceMedium==google / cpc</strong></blockquote><p>and finally, use this filter to get all ga:sourceMedium combinations that contain “Google”:</p><blockquote><strong>ga:sourceMedium=~google</strong></blockquote><p>As you can see from the above, I used<strong> “==”</strong> to filter for a specific ga:sourceMedium (i.e. “google / organic”), I used <strong>“=~”</strong> to filter for ga:sourceMedium containing a word “google”.</p><p>Also, I used <strong>“,”</strong> to specify several filters, in which case I got the results that include ga:sourceMedium of “google / organic” OR “google / cpc”. The final combination would be to list filters separated with “;”, which stands for “AND” logical operator:</p><blockquote><strong><em>ga:sourceMedium=~google; ga:sourceMedium=~cpc</em></strong></blockquote><p>Thus, the above will filter ga:sourceMedium that contains (“=~” operator used) “google” AND “cpc”, and would be identical to</p><blockquote><strong><em>ga:sourceMedium==google / cpc</em></strong></blockquote><p>Try it out as filters are a super powerful feature of the API.</p><p>In addition, you can sort the resulting data by the dimensions you specify and <strong>you can specify multiple dimensions to sort with</strong> (just separate them with commas). In case multiple dimensions are specified, the resulting data will be sort by the first specified dimensions, then by the second, then by the third, etc.</p><p><strong>Start-date &amp; End-date<br></strong>Selecting date range is straight forward; however, it is important to pay attention to <strong>“This result is based on sampled data”</strong> warning. In case you receive this warning (next to “Get Data” button as in the image below), I suggest you to try selecting a shorter date range until you get rid of the warning. In some cases it want help, as you might be operating with a large dataset (i.e. trying to get each pageview by minute) and yet, shortening the date range can help quite often.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MEBEGp61WpuaM39gXhyXg.png" /></figure><p>You can read more about Data Sampling in Google Analytics <a href="https://developers.google.com/analytics/resources/concepts/gaConceptsSampling">here</a>.</p><p><strong>Max-result and Start-index<br></strong>Query Explorer will return the number of rows limited by the <strong>“max-result”</strong> field (10,000 in the example below). Similarly, to the Reporting API, the <strong>maximum number of rows to be returned is 10,000;</strong> however, <strong>you can use “start-index” field to get more than 10,000 rows</strong>.</p><p>Take a look at the example below: my query matched 23110 results, and as the “max-result” field was set to 10,000, Query Explorer returned exactly 10,000 rows, from 1 to 10,000. So how do I get the rows 10,001 to 23,110? By specifying the “start-index” parameter: if I set it to 2, then the rows 10,001 to 20,000 will be returned, if I set it to 3 then the rows 20,001–23,110 will be returned (there are just 23,110 results in this query, otherwise rows 20,001 to 30,000 would be returned).</p><p>Therefore, if you query returns more than 10,000 results, use “start-index” to iterate through those.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqJJIeQX_S9PuH05O8UpNw.png" /></figure><p>That would be pretty much it on formulating queries, so just <strong>hit the “Get Data” button to see your data</strong>. Don’t worry about making mistakes, Query Explorer error warnings are really helpful in formulating the query correctly.</p><p>Once you get comfortable with Query Explorer you will be able to get any data out of Google Analytics sliced by the dimensions you want.</p><h4>Exporting Data and Sharing Queries</h4><p>Once you have formulated the query and validated that it outputs the correct data, <strong>you can export the data into .TSV file</strong> (tab separeted values) by clicking “Excel TSV” button on the right.</p><p>In addition, <strong>you can share the result with your colleagues or clients</strong>: by clicking the “Share Report” button (as shown in the image below), you’ll get a link to Query Explorer with the query you formulated.</p><blockquote><strong>It is important to note, that sharing a link will only share the query (the values of the dimensions, metrics, segments, filters, etc fields that you have specified) and will not share any Google Analytics data.</strong></blockquote><p>In order, to run the query, a person receiving the link will need to have access to the correct Google Analytics Account, Property and View.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*7aR1M85MCK63r29_y9n4-g.png" /></figure><p>Finally, as Query Explorer is ideal for building regular reports (i.e. weekly AdWords campaign performance), you can <strong>save a link to the formulated query in a text file or a spreadsheet, and then reuse it whenever you have to run this report again</strong>.</p><p>Alternative, you can build a whole library of queries for all use cases:</p><ul><li><a href="https://ga-dev-tools.appspot.com/explorer/?dimensions=ga%253AoperatingSystem%252Cga%253Abrowser%252Cga%253AbrowserVersion&amp;metrics=ga%253Ausers&amp;start-date=2014-12-01&amp;end-date=2014-12-31&amp;max-results=10000">Users shown by Operating System, Browser and Browser Version</a></li><li><a href="https://ga-dev-tools.appspot.com/explorer/?dimensions=ga%253Adate&amp;metrics=ga%253Aimpressions%252Cga%253AadClicks%252Cga%253AadCost%252Cga%253ACPM%252Cga%253ACPC%252Cga%253ACTR&amp;start-date=2014-12-01&amp;end-date=2014-12-31&amp;max-results=10000">AdWords Impressions, Clicks, Cost, CPM, CPC shown by date</a></li><li><a href="https://ga-dev-tools.appspot.com/explorer/?dimensions=ga%253Adate&amp;metrics=ga%253Ausers&amp;filters=ga%253AfullReferrer%253D~facebook&amp;start-date=2014-12-01&amp;end-date=2014-12-31&amp;max-results=10000">Users referred by Facebook shown by date</a></li><li>and so on…</li></ul><p>Hope this helps and don’t forget to visit my other tutorials:</p><ul><li><a href="https://medium.com/p/bc5a43537e23"></a></li><li><a href="https://medium.com/p/7f1d59d794f5"></a></li><li><a href="https://medium.com/p/ec8019535da"></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ae3ed74667" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Import Data from Google Analytics into Google Sheets with Google Apps Script]]></title>
            <link>https://medium.com/@jev/how-to-import-data-from-google-analytics-into-google-sheets-with-google-apps-script-5174a10b24d8?source=rss-8e7b507d5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/5174a10b24d8</guid>
            <dc:creator><![CDATA[Jevgenijs Kazanins]]></dc:creator>
            <pubDate>Wed, 05 Nov 2014 01:33:31 GMT</pubDate>
            <atom:updated>2014-12-25T12:39:07.552Z</atom:updated>
            <content:encoded><![CDATA[<h2>How to Import Data from Google Analytics into Google Sheets with<br>Apps Script</h2><p>At some point I got curious about how to get data from different API, such Google Analytics API, into Google Sheets. (not)Surprisingly there was a ready solution for that called <a href="https://developers.google.com/apps-script/">Google Apps Script</a>. So <strong>if you are tired of regularly exporting data from Google Analytics API, importing it into Excel and making the same report over and over again, then this post is for you!</strong> In this blog post I will explain :</p><ol><li>How to get started with Google Apps Scripts</li><li>How to get data from Google Analytics Core Reporting API and insert it into Google Sheet</li><li>How to use cell values to specify parameters for Google Analytics API request</li></ol><p>At the end of this post you should have Google Sheet that a) captures parameters (i.e. metrics that you want to get from Google Analytics API) from one sheet, b) gets the data using those parameters from Google Analytics API, and c) insert the result into a new sheet.</p><p><strong>Hint: if reading the rest of the post doesn’t sound like fun, just open this shared </strong><a href="https://docs.google.com/spreadsheets/d/17GREFWla2tgks8i7qplvyRl1KJii5Ca8yH51MTdxAcU/edit?usp=sharing"><strong>Google Sheet</strong></a><strong> to see the end result. Feel free to make a copy of it and use it as you wish.</strong></p><h3>Getting Started with Google Apps Scripts</h3><ol><li>Create a new Google Sheet</li><li>Navigate to Tools -&gt; Script Editor</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*HnoOUuALOZecstZ5j9d7Ug.png" /></figure><p>3. Select Blank Project in the popup window</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*ezPnTHb9LNnBgFkzHdki_Q.png" /></figure><p>4. Paste the following code on the Script Editor window and click Save:</p><pre>function onOpen() {<br> var ui = SpreadsheetApp.getUi();<br> <br> ui.createMenu(‘Get external data’)<br> .addItem(‘Google Analytics’, ‘getGoogleAnalyticsData’)<br> .addToUi();<br>}</pre><pre>function getGoogleAnalyticsData() {<br> SpreadsheetApp.getUi().alert(‘You clicked Get external data -&gt; Google Analytics menu item!’);<br>}</pre><p>5. If you go back to the Google Sheet that you started with and click refresh (Script editor tab will close, but don’t worry about that), you will be able to see a new menu item called “Get External Data”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*Fs8rXWybwFMfJUG5xAempw.png" /></figure><p>Try clicking on the “Google Analytics” item in the menu and you will see a small popup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIDyIB9naLfIpf_u-i0T8A.png" /></figure><p>Now let’s walk through what we just did to understand how Apps Script work (in a simple, marketer to marketer, terms):</p><p>We created an Apps Script that is associated with the Google spreadsheet. The Apps Script (for now) has two functions (select Tools -&gt; Script Editor to get back to the Editor and see the code.</p><pre><strong>function onOpen() {</strong><br> var ui = SpreadsheetApp.getUi();<br> <br> ui.<strong>createMenu</strong>(‘Get external data’)<br> .<strong>addItem</strong>(‘Google Analytics’, ‘getGoogleAnalyticsData’)<br> .addToUi();<br><strong>}</strong></pre><p>function onOpen() {} is <strong>fired automatically when the subject Google spreadsheet is opened</strong> (here’s why the name). For the future, the easiest way to run some code each time a document is opened is to put it into onOpen() function.</p><p>In this case we create a new Menu named “Get external data”, <strong><em>createMenu(‘Get external data’)</em></strong><em>,</em> as well as one Menu Item named “Google Analytics, <strong><em>addItem(‘Google Analytics’.</em></strong><em>‘getGoogleAnalyticsData’).</em></p><p>The most important part here, is that we define what happens when a user clicks the Menu item “Google Analytics” and we do that be specifying a function name, <strong>getGoogleAnalyticsData,</strong> to execute once this menu item is selected.</p><pre>addItem(‘Google Analytics’.‘<strong>getGoogleAnalyticsData</strong>’)</pre><p>Simple, right? Now, all is left is to write that <strong>getGoogleAnalyticsData</strong> function, which we do in the rest of the code:</p><pre><strong>function getGoogleAnalyticsData() {</strong><br> SpreadsheetApp.getUi().alert(‘You clicked Get external data -&gt; Google Analytics menu item!’);<br><strong>}</strong></pre><p>The code between the brackets {} just creates a popup for now, but in the <strong>next part of the post we will write a script that will get data from Google Analytics</strong>.</p><h3>Getting Data from Google Analytics API</h3><p>Google offer <a href="https://developers.google.com/apps-script/advanced/analytics#run_a_report">a great example</a> on querying Google Analytics API using Apps Script, so let’s use it! (and my two cents will be in explaining what this code does.</p><p>Open Script Editor and replace <strong>function getGoogleAnalyticsData() {…}</strong> with this code:</p><pre><strong>function getGoogleAnalyticsData() {</strong></pre><pre>var today = new Date();<br>var oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);<br><br>var startDate = Utilities.formatDate(oneWeekAgo, Session.getTimeZone(),&#39;yyyy-MM-dd&#39;);<br>var endDate = Utilities.formatDate(today, Session.getTimeZone(),&#39;yyyy-MM-dd&#39;);<br><br>var tableId  = &#39;ga:83819930&#39;;<br>var metric = &#39;ga:visits&#39;;<br>var options = {<br>    &#39;dimensions&#39;: &#39;ga:source,ga:keyword&#39;,<br>    &#39;sort&#39;: &#39;-ga:visits,ga:source&#39;,<br>    &#39;filters&#39;: &#39;ga:medium==organic&#39;,<br>    &#39;max-results&#39;: 25<br>};<br>var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,options);<br><br>if (report.rows) {<br>  var spreadsheet = SpreadsheetApp.getActive();<br>  var sheet = spreadsheet.getActiveSheet();<br><br>  var headers = report.columnHeaders.map(function(columnHeader) {<br>      return columnHeader.name;<br>  });<br>  sheet.appendRow(headers);<br><br>  sheet.getRange(2, 1, report.rows.length, headers.length)<br>        .setValues(report.rows);<br>} else {<br>    Logger.log(&#39;No rows returned.&#39;);<br>}<br>}</pre><p>Now let’s go through what is happening in this code:</p><pre><strong>var today = new Date();</strong><br><strong>var oneWeekAgo</strong> = new Date(today.getTime() - <strong>7 * 24 * 60 * 60 * 1000</strong>);<br><br>var startDate = Utilities.formatDate(oneWeekAgo, Session.getTimeZone(),&#39;yyyy-MM-dd&#39;);<br>var endDate = Utilities.formatDate(today, Session.getTimeZone(),&#39;yyyy-MM-dd&#39;);</pre><p>You can ignore most of this part, what is important is that it defines a variable <strong>today</strong> and gives it a value of now (meaning the day and time you run this script), as well as defines a variable <strong>oneWeekAgo</strong> and gives it a value of one week ago from now (or rather one week ago from the day and time you run this script).</p><p><strong>As you can see to get to one week ago you do simple calculus: (days) * (hours in a day) * (minutes in an hour) * (seconds in a minute) * 1000. </strong>Last multiplication by 1000 is needed as the value of the variable is in milliseconds. So to get 365 days back you do:</p><pre><strong>var oneYearAgo</strong> = new Date(today.getTime() - <strong>365</strong> * 24 * 60 * 60 * 1000);</pre><p>The rest of the code in this part just converts the dates of today and oneWeekAgo into a format that is acceptable by Google Analytics API, so let’s move on:</p><pre>var <strong>tableId</strong> = &#39;ga:83819930&#39;;<br>var <strong>metric</strong> = &#39;ga:visits&#39;;<br>var options = {<br> &#39;<strong>dimensions</strong>&#39;: &#39;ga:source,ga:keyword&#39;,<br> &#39;<strong>sort</strong>&#39;: &#39;-ga:visits,ga:source&#39;,<br> &#39;<strong>filters</strong>&#39;: &#39;ga:medium==organic&#39;,<br> &#39;<strong>max-results</strong>&#39;: 25<br>};</pre><p>This part of the code defines the parameters of the request we are going to make to Google Analytics API. If you know all of those, lucky you, for the rest of us I suggest <a href="https://ga-dev-tools.appspot.com/explorer/">Google Analytics Query Explorer</a> (which is especially helpful in finding tableId).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXInRbeG8WkSvjiOjolRRQ.png" /></figure><pre>var <strong>tableId</strong> = &#39;ga:83819930&#39;;</pre><p>This the the <strong>ID of the Google Analytics View</strong> (not Account, not Property, but View) from which we want to get the data. <strong>In the above code you need to write tableId for one of the Google Analytics Views that you have access to</strong>. You can find it either using Query Explorer like in the picture above, or in Google Analytics -&gt; Admin -&gt; View Settings (just don’t forget to add “ga:” before the actual ID):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*So6mXQ9Nt1uJTIF7MtXojw.png" /></figure><pre>var <strong>metric</strong> = &#39;ga:visits&#39;;<br>var options = {<br> &#39;<strong>dimensions</strong>&#39;: &#39;ga:source,ga:keyword&#39;,<br> &#39;<strong>sort</strong>&#39;: &#39;-ga:visits,ga:source&#39;,<br> &#39;<strong>filters</strong>&#39;: &#39;ga:medium==organic&#39;,<br> &#39;<strong>max-results</strong>&#39;: 25<br>};</pre><p>The above defines the metrics, dimensions, filter and sorting options we are going to request from Google Analytics API. <strong>The “max-results” parameter can be set to 10,000, which is the absolute limit per Google Analytics API request. Thus, if you plan to retrieve more data, you will need to break down your query into parts (which Apps Script can easily help with!)</strong>.</p><p>Finally we make a request to Google Analytics API:</p><pre>var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,options);</pre><p>The response from the API is now store in the variable report; thus, the first thing we do is check if that variable has any data, and if it doesn’t we write to the log a message “No rows returned”:</p><pre>if (report.rows) {<br> ...</pre><pre>} else { <br>  Logger.log(&#39;No rows returned.&#39;);<br>}</pre><p>Log is extremely helpful tool, as it allows to you detect the problems that might be happening during the code execution. For instance, in this case if you run a script and nothing happens, you should check the log. <strong>If the log has the message “No rows returned” then most likely nothing happens because you formulated the API query parameters incorrectly</strong>.</p><p>You can access the log from Script Editor: View -&gt; Log:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*3OFq35oIPWNvrkiDcmP90A.png" /></figure><p>But let’s see what happens if the API does return some data:</p><pre>var spreadsheet = SpreadsheetApp.getActive();<br>var sheet = spreadsheet.getActiveSheet();</pre><p>The above code represents the very beauty of Google Apps Script: in just two simple lines you got hold of the active sheet, <strong>spreadsheet.getActiveSheet()</strong> in the active Google spreadsheet file, <strong>SpreadsheetApp.getActive()</strong> , and now can write data directly to the spreadsheet!</p><pre>var headers = report.columnHeaders.map(function(columnHeader) {<br> return columnHeader.name;<br> });<br><strong>sheet.appendRow(headers);</strong></pre><p>The first line is some fancy Javascript code (ok, not so fancy, but fully understanding it is beyond the scope of this post) that get the <strong>headers from the API response, which are ga:source, ga:keyword, ga:visits </strong>(remember what we specified in the API query? exactly those!).</p><p>The second line appends (meaning adding to the last non-empty row) a row with header values in the active sheet in the active spreadsheet, because earlier we define <strong>sheet</strong> as active sheet:</p><pre>var sheet = spreadsheet.getActiveSheet();</pre><p>in the active <strong>spreadsheet</strong>:</p><pre>var spreadsheet = SpreadsheetApp.getActive();</pre><p>Finally, we also add data we got back from the Google Analytics API to the same sheet:</p><pre>sheet.<strong>getRange</strong>(2, 1, report.rows.length, headers.length)<br> .<strong>setValues</strong>(<strong>report.rows</strong>);</pre><p>A couple of important things here to understand what this line of code does:</p><blockquote><a href="https://developers.google.com/apps-script/reference/spreadsheet/sheet#getRange(Integer,Integer,Integer,Integer)">getRange(row, column, numRows, numColumns</a>)<br>gets a range, or selects several cells in the active sheet</blockquote><p><strong>In this example, row = 2, column = 1, numRows = number of rows in the the API response (report.rows.length), numColums = number of headers returned by the API call (headers.length).</strong></p><blockquote>.setValues()<br>sets the value of the range that we got by calling getRange</blockquote><p><strong>In this example we set the values of this range to the values of the Google Analytics API response, which are stored in <em>report.rows</em>.</strong></p><p>Apps Script will do the magic and put value into respective cells, despite the fact that report.rows is actually a table, or array, not a single value.</p><p><strong>Let’s finally run the code! Menu -&gt; Get external data -&gt; Google Analytics! The below part is super important to actually be able to run your code.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*F4BMSgvFxtPWtskDe2SqJw.png" /></figure><p>Here comes the first authorization that we need to make to run the code. Click continue and grant requested permissions (don’t worry this is your app, and I hope you should be safe by giving your own app access to your data).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewM4F4kAb0THtXk4IcIWEg.png" /></figure><p>Did you get that red alert “<strong>ReferenceError: “Analytics” is not defined.DetailsDismiss”? That’s good, it means we’re on the right track!</strong></p><p>Navigate to Tools -&gt; Script Editor and in the Editor navigate to Resources -&gt; Advanced Google Services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6yDYiGbN41Bt_U9_1VdyQ.png" /></figure><p>Turn on Google Analytics API (<strong>DO NOT click OK just yet!</strong>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*b7XnKI9CcK1v5U1kYHnnAg.png" /></figure><p>Now click the link Google Developers Console, which will open Developers Console. Now find Google Analytics API in the list and turn it on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUx9jel3KQI2xF3ZuoE-MA.png" /></figure><p>Now you can finally click OK in one the popup window in Script Editor. Navigate back to the spreadsheet and run the code again.</p><p><strong>There will be one more Access request, this time for accessing your Google Analytics data (again, don’t worry, this is your app and you give access only to this app).</strong></p><p><strong>If you didn’t forget to change tableId to the Google Analytics View ID, which you have access to then you should see the result in the spreadsheet:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*O5VSCY4iFGAkjGCINLLufw.png" /></figure><p>Awesome, isn’t it? Now let’s make it a bit more usefull!</p><h3>Use Cell Values to Specify Parameters for Google Analytics API Request</h3><p>We all probably were (or are) in situations where we needed to send regular reports to bosses or clients. We’d get the same data from Google Analytics, put into Excel and send the report. Let’s try to make this task easier with Google Apps Script!</p><p>First, I will add another menu item to our Get external data menu:</p><pre>function onOpen() {<br> var ui = SpreadsheetApp.getUi();<br> <br> ui.createMenu(&#39;Get external data&#39;)<br> .addItem(&#39;Google Analytics&#39;, &#39;getGoogleAnalyticsData&#39;)<br> <strong>.addItem(&#39;Create report&#39;, &#39;createReport&#39;)</strong><br> .addToUi();<br>}</pre><p>I will also create a separate sheet with parameters for the query (as you can see I used VLOOKUP function to lookup tableId from the list at the bottom; collecting those IDs once will simplify the work in the future), as well as the name of the sheet that the report will be stored in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*85kiuoNpjaHSnYSyI_FCyQ.png" /></figure><p>Here is the code I wrote for the function <strong>createReport:</strong></p><pre>function createReport() {<br> var spreadsheet = SpreadsheetApp.getActive();<br> var sheet = spreadsheet.getSheetByName(&#39;params&#39;);<br> <br> var start = new Date(sheet.getRange(2, 3, 1, 1).getValues());<br> var end = new Date(sheet.getRange(3, 3, 1, 1).getValues());<br> <br> var startDate = Utilities.formatDate(start, Session.getTimeZone(),&#39;yyyy-MM-dd&#39;);<br> var endDate = Utilities.formatDate(end, Session.getTimeZone(),&#39;yyyy-MM-dd&#39;);<br> <br> var tableId = String(sheet.getRange(5, 3, 1, 1).getValues());<br> var metric = String(sheet.getRange(6, 3, 1, 1).getValues());<br> var options = {<br> &#39;dimensions&#39;: String(sheet.getRange(7, 3, 1, 1).getValues()),<br> &#39;sort&#39;: String(sheet.getRange(8, 3, 1, 1).getValues()),<br> &#39;filters&#39;: String(sheet.getRange(9, 3, 1, 1).getValues()),<br> &#39;max-results&#39;: String(sheet.getRange(10, 3, 1, 1).getValues())<br> };<br> Logger.log(tableId);<br> var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,options);<br> <br> if (report.rows) {<br> var reportsheet = spreadsheet.getSheetByName(String(sheet.getRange(11, 3, 1, 1).getValues()));<br> if(reportsheet) {<br> spreadsheet.deleteSheet(reportsheet);<br> }<br> <br> var reportsheet = spreadsheet.insertSheet(String(sheet.getRange(11, 3, 1, 1).getValues()));<br> var headers = report.columnHeaders.map(function(columnHeader) {<br> return columnHeader.name;<br> });<br> reportsheet.appendRow(headers);<br> <br> reportsheet.getRange(2, 1, report.rows.length, headers.length)<br> .setValues(report.rows);<br> <br> Logger.log(&#39;Report spreadsheet created: %s&#39;,<br> spreadsheet.getUrl());<br> } else {<br> Logger.log(&#39;No rows returned.&#39;);<br> }<br>}</pre><p>As you can see, I didn’t add many new things. Just few simple ones:</p><pre>var sheet = spreadsheet.getSheetByName(&#39;params&#39;);</pre><p>Previously, we selected an active sheet, but in this example I am selecting a sheet by name (“params”). I later get value for the API query from this sheet:</p><pre>sheet.getRange(5, 3, 1, 1).getValues()</pre><p>We discussed getRange, but getValues() is as simple as getting the values from that range. I later convert it into String(), so Google Analytics API can accept it:</p><pre>String(sheet.getRange(5, 3, 1, 1).getValues())</pre><p>Finally, I create a new sheet based on the name indicted in the “params”:</p><pre>spreadsheet.insertSheet(String(sheet.getRange(11, 3, 1, 1).getValues()));</pre><p>That’s it! Open the<strong> </strong><a href="https://docs.google.com/spreadsheets/d/17GREFWla2tgks8i7qplvyRl1KJii5Ca8yH51MTdxAcU/edit?usp=sharing"><strong>final Google Sheet</strong></a>, make a copy and feel free to use it. Hope this helps!</p><p><strong>p.s. the same can be done to get data from Facebook API, Twitter API, YouTube API, Mailchimp API and AnyOtherAPI! ;) Ping me on Twitter (</strong><a href="https://twitter.com/jevgenijs"><strong>@jevgenijs</strong></a><strong>) if you want me two write a blog post on using other APIs with Google Apps Script.</strong></p><p>p.s.s. Thanks to brillian folks at Google for creating Apps Script and the great <a href="https://developers.google.com/apps-script/advanced/analytics">tutorial</a> on how to get started.</p><ul><li><a href="https://medium.com/p/62ae3ed74667"></a></li><li><a href="https://medium.com/p/7f1d59d794f5"></a></li><li><a href="https://medium.com/p/bc5a43537e23"></a></li></ul><p><em>Image: </em><a href="http://wallpoper.com/"><em>http://wallpoper.com/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5174a10b24d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to JQuery for Marketers]]></title>
            <link>https://medium.com/@jev/introduction-to-jquery-for-marketers-bc5a43537e23?source=rss-8e7b507d5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc5a43537e23</guid>
            <dc:creator><![CDATA[Jevgenijs Kazanins]]></dc:creator>
            <pubDate>Tue, 14 Oct 2014 14:36:57 GMT</pubDate>
            <atom:updated>2014-12-25T13:34:24.045Z</atom:updated>
            <content:encoded><![CDATA[<h4>a 10 minute crash course to get you started with JQuery</h4><p>JQuery can be a powerful instrument in any digital marketer’s toolbox. I wrote earlier on how to use JQuery to <a href="https://medium.com/@jev/how-to-run-optimizely-experiments-without-screwing-up-your-website-ec8019535da">run pixel-perfect A/B experiments with Optimizely</a> and how to style a page by injecting JQuery with <a href="https://medium.com/@jev/10-cool-things-you-can-do-with-google-tag-manager-7f1d59d794f5">Google Tag Manager</a>, but application of JQuery goes way beyond that.</p><p>I strongly believe that every digital marketer needs to be comfortable with at least the basics of HTML, CSS and JQuery and hope this post will help some of you get started with JQuery.</p><h4>Why use JQuery?</h4><p>In some cases HTML and CSS are not enough. If HTML defines the structure, elements and order of elements of a page, and CSS defines how elements of the page are displayed, then <strong>JQuery allows manipulating those elements</strong>.</p><p>Here are a few things you can do with JQuery:</p><ul><li>Change attributes of elements, such as <em>class</em>, <em>value</em>, <em>style</em>;</li><li>Change order of elements (i.e. rearrange items in the list);</li><li>Add new elements to a page (from simple text to HTML blocks);</li><li>Add interaction to elements (i.e. show warning when a button is clicked)</li></ul><p>From my experience, I found that creating A/B experiments almost always requires the use of JQuery. You can get along with drag-and-drop functionality of Optimizely and custom CSS styling, but more complex experiments usually require a more advanced tweaking of the langing page.</p><p>Another use case is that in some case you might need to implement changes to a website very fast and the engineering resources are not available. In that case you can implement the changes by injecting JQuery code with Google Tag Manager.</p><h4>Running JQuery on your website</h4><p>First of all, for the JQuery commands to run on your page <strong>you need the JQuery library to be included on your page</strong> which usually is done by including the following line in the &lt;head&gt; section of the page:</p><blockquote>&lt;script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js&quot;&gt;&lt;/script&gt;</blockquote><p>If JQuery library is included on your page, you’re good to go with writing your code (just don’t forget to wrap it with &lt;script&gt;&lt;/script&gt;). There are several options for running JQuery code on your website:</p><ul><li>Include it in the page code (through your Content Management System)</li><li>Inject it with Google Tag Manager (as a custom HTML tag)</li><li>Inject it with Optimizely (through &lt;edit code&gt; section)</li></ul><p>A useful tool for developing and testing your JQuery code is Console, which is part of Chrome Developer Tools (but any modern browser has a similar functionality). Open your website in a browser and hit <em>Ctrl + Shift + J</em> on Windows or <em>Cmd + Opt + J </em>on Mac.</p><p>Now paste a line of JQuery code and hit Enter. If the code has no mistakes the command will be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*OqcKqDBRFdBj7FdR92QhMA.jpeg" /></figure><p>In the example above I removed an element with a class <em>.hero-title</em>, which is was my name. I use <a href="http://www.sublimetext.com/">Sublime Text</a> for writing code, as it gives syntax highlighting making spotting errors much easier. Then I use Console to test the code (you can paste and execute multiple commands in one go.</p><h4>Structure of JQuery commands</h4><p>In order to write JQuery code you need to understand how the commands are structured. <strong>There are three elements in each JQuery command</strong>:</p><blockquote>$(‘<strong>element selector</strong>’).<strong>function</strong>(‘<strong>parameters</strong>’);</blockquote><p><strong><em>element selector</em></strong>: defines which page element to apply JQuery function to.</p><p><strong><em>function</em></strong>: defines JQuery function to apply. Bookmark <a href="http://api.jquery.com/">this reference</a> to see the full list of JQuery functions available for your choice.</p><p><strong><em>parameters</em></strong>: some of JQuery functions require parameters, some don’t (in this case you’d just leave empty brackets, i.e. <em>remove()</em>.</p><p>Here are a few examples:</p><blockquote>$(‘.footer’).remove();</blockquote><p>The above live selects the element with class <strong>“footer”</strong>, and applies <em>remove()</em> function to it (which obviously, removes the element). <a href="http://api.jquery.com/remove/"><em>remove()</em></a> function doesn&#39;t require any parameters.</p><blockquote>$(.header).append(‘&lt;p&gt;Extra line of text appended to header&lt;/p&gt;’);</blockquote><p>The above selects the element with class <strong>“header”</strong>, and applies append() function to it. <a href="http://api.jquery.com/append/"><em>append()</em></a> inserts the parameter passed in the brackets, in this case it inserts <em>&lt;p&gt;Extra line of text appended to header&lt;/p&gt;.</em></p><h4>Selecting the right element</h4><p>In order to select the correct page element you need a bit of CSS knowledge, or <strong>you can use Element Inspector functionality of Chrome Developer Tools</strong>. To open Element Inspector, open the website in Chrome (again, both Firefox and Safari have similar functionality), select the element that you want to apply JQuery function to, right click and select “Inspect Element”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJkLghFEwqlutZ6hP0AyTg.png" /></figure><p>Element Inspector will highlight the HTML code that renders the element that you selected, which helps you in finding the class and/or id of the element and thus, structure the selector. Below I show the basic syntax for selecting the element using it’s class and id.</p><blockquote><strong>#</strong>important-list // # symbol followed by the name</blockquote><p>selects an element with id=”important-list”, for instance<br>&lt;ul id=”important-list”&gt;|<br>…<br>&lt;/ul&gt;</p><blockquote>.important-list // . followed by the name</blockquote><p>selects an element with class=”important-list”, for instance<br>&lt;div class=”important”&gt;<br>…<br>&lt;/div&gt;</p><blockquote>.important-list:first-child, .important-list:last-child and nth-child(0)</blockquote><p>selects either first, last or specific “child” of an element, for instance<br>&lt;div class=”important-list”&gt; &lt;div&gt; … &lt;/div&gt; // .important-list:first-child &lt;div&gt; … &lt;/div&gt; // .important-list:nth-child(2) &lt;div&gt; … &lt;/div&gt; // .important-list:last-child</p><p>Alternatively, you right click on the element in Element Inspector and select “Copy CSS Path”, which will copy the selector of the element into the clipboard. Warning: you better learn how to write selectors on your own, as “Copy CSS Path” is not ideal.</p><h4>Frequently used functions</h4><p>As we now discussed why and how to run JQuery code, let’s dig into the most interesting part and explore some of the most frequently used functions:</p><p><strong>Changing content of existing elements:</strong></p><blockquote><a href="http://api.jquery.com/html/"><strong>.html()</strong></a></blockquote><p>The above function allows you replacing the content of an element. For instance you if you want to change the text of H1 you run:</p><blockquote>$(‘h1<em>’</em>).html(‘New and better header’);</blockquote><p>Or you might be interested in changing a bigger element, such as footer:</p><blockquote><em>$(‘.footer</em>’).<em>html(‘&lt;div class=”footer-container”&gt;….&lt;/div&gt; ’);</em></blockquote><p>.html() allows you to replace pretty much anything on the website (if used right. Hint: want to replace the whole page? Try $(‘body’).html(‘’);</p><p><strong>Adding new elements to the page:</strong></p><blockquote><a href="http://api.jquery.com/append/"><strong>.append()</strong></a><strong>, </strong><a href="http://api.jquery.com/prepend/"><strong>.prepend</strong></a><strong>, </strong><a href="http://api.jquery.com/after/"><strong>.after()</strong></a></blockquote><p>All three functions allow adding extra element to the page with the only difference being the location of where the element will be added at. For instance running</p><blockquote>$(‘.footer’).after(‘&lt;p&gt;Paragraph that follows the footer&lt;/p&gt;’);</blockquote><p>will add a paragraph AFTER the closing &lt;/div&gt; of the element &lt;div class=”footer”&gt;&lt;/div&gt;.</p><p><strong>Changing class and style attributes of elements:</strong></p><blockquote><a href="http://api.jquery.com/attr/"><strong>.attr()</strong></a></blockquote><p>This function allows you changing the attributes of an element such as class, style or value. For instance, the below</p><blockquote>$(‘#important-list’).attr(‘class’,’no-bullet-list’);</blockquote><p>will change the class attribute to “no-bullet-list” of an element with id=”important-list”, so it would become</p><p>&lt;div id=”important-list” class=”no-bullet-list”&gt; … &lt;/div&gt;</p><p>Alternatively, you can use .attr() to add CSS styling to an element:</p><blockquote><em>$(‘#important-list’).attr(‘style’,’text-decoration:none;’);</em></blockquote><p>which would change style attribute of important-list attribute:</p><p>&lt;div id=”important-list” style=”text-decoration:none;”&gt; … &lt;/div&gt;</p><p><strong>Wrapping element:</strong></p><blockquote><a href="http://api.jquery.com/wrap/"><strong>.wrap()</strong></a></blockquote><p>In some cases you want to wrap an element with extra &lt;div&gt;&lt;/div&gt; to apply extra CSS styling. Running</p><blockquote>$(‘.footer’).wrap(‘&lt;div class=”extra-footer-wrapper” /&gt;’);</blockquote><p>will wrap the element with class=”footer” into</p><blockquote><em>&lt;div class=”extra-footer-wrapper”&gt; &lt;div class=”footer”&gt; …<br>&lt;/div&gt;<br>&lt;/div&gt;</em></blockquote><p><strong>Changing order of elements:</strong></p><blockquote><a href="http://api.jquery.com/insertbefore/"><strong>.insertBefore()</strong></a><strong> and </strong><a href="http://api.jquery.com/insertafter/"><strong>.insertAfter()</strong></a></blockquote><p>What if you want to reorder element on your page? Let’s say you want to display button with id=”botton-2&quot; BEFORE the button with id=”button-1&quot;:</p><blockquote>$(‘#button-1’).insertBefore(‘#button-2’);</blockquote><p>the above will take the element with id=”button-2&quot; and insert it before the element with the id=”button-2&quot;.</p><p><strong>Removing elements:</strong></p><blockquote><a href="http://api.jquery.com/remove/"><strong>.remove()</strong></a></blockquote><p>Removing elements is super easy:</p><blockquote>$(‘#button-1’).remove();</blockquote><p>the above will remove an element with id=”button-1&quot; from the page completely.</p><p>Time to wrap up. As I mention earlier, visit <a href="http://api.jquery.com/">JQuery API Documentation</a> for more functions to add to you toolbox or just google it, as there is plenty of information about JQuery on the Internet.</p><p>Hope this will get you started with JQuery, but feel free to ping me on Twitter (<a href="https://twitter.com/jevgenijs"><strong>@jevgenijs</strong></a>) if you need more tips.</p><p><em>p.s. thanks to </em><a href="https://www.periscope.io/blog/sql-for-marketers.html"><em>Periscope.io</em></a><em> for the inspiration!</em></p><h4>Check out my other blog posts:</h4><ul><li><a href="https://medium.com/p/7f1d59d794f5"></a></li><li><a href="https://medium.com/p/ec8019535da"></a></li><li><a href="https://medium.com/p/62ae3ed74667"></a></li></ul><p><em>Image: </em><a href="http://www.student.ugent.be/"><em>http://www.student.ugent.be/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc5a43537e23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run Optimizely experiments without screwing up your website]]></title>
            <link>https://medium.com/@jev/how-to-run-optimizely-experiments-without-screwing-up-your-website-ec8019535da?source=rss-8e7b507d5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec8019535da</guid>
            <dc:creator><![CDATA[Jevgenijs Kazanins]]></dc:creator>
            <pubDate>Sat, 11 Oct 2014 09:13:23 GMT</pubDate>
            <atom:updated>2014-10-11T09:13:23.025Z</atom:updated>
            <content:encoded><![CDATA[<h4>tricks that will help you run pixel-perfect experiments</h4><p><a href="https://www.optimizely.com/"><strong>Optimizely</strong></a><strong> is an absolutely amazing A/B testing and conversion optimization platform!</strong> If you are reading this post then you are most likely familiar with both A/B testing and Optimizely, but in a nutshell, the solution allows you to test different variation of a page (i.e. one with a call-to-action “Sign up for free” and another one with a call-to-action “Open your account now”) to determine, which version converts better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*JQkg5-sIPCO-QD3HunyuZQ.png" /></figure><p>A/B testing is nothing new, but what Optimizely brought to the table is the <strong>ability for marketers to run optimization tests without involving engineers</strong>. Instead of asking your engineering team to create multiple versions of a landing page that you want to test, Optimizely gives you an drag-and-drop interface to create multiple versions of the page and than handles traffic allocation and tracking.</p><blockquote>However, the ease of use comes with a cost. Namely, irrespectively of how good drag-and-drop functionality is, it can totally ruin your website. Sign up forms that don’t submit, buttons that don’t work, distorted page layout, and so on.</blockquote><p>Without going into much detail, <strong>Optimizely uses JQuery to create variations of your landing page</strong>. For instance, if I’d like to experiment with the “Follow” button on my Medium blog (to see if “Follow Jevgenijs on Medium” converts better), I’d select the “Follow” button and select “Edit Text”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vvv4a-qcKO6BtFf439NTMA.png" /></figure><p>What happens under the hood, is that this change would be executed through a piece of JQuery code:</p><blockquote>$(“.button—large”).html(“&lt;span class=\”button-label follow-label\” data-suffix=\”ing\”&gt;Follow Jevgenijs on Medium&lt;/span&gt;”);</blockquote><p>For those familiar with JQuery, it is clear from the code that Optimizely implements the change by replacing the html code of the .button-large element. The above example will run smoothly; however, if you <strong>try to adjust more complex elements on your landing page, such as sign up forms, it can result in a complete disaster</strong>.</p><blockquote>Nevertheless, why I love Optimizely is because it gives you enough flexibility to be in total control of how your test variations are created!</blockquote><p>Below, I list a few ways to run pixel-perfect experiments.</p><h4>Copy/paste entire HTML blocks</h4><p>The easiest way to run experiments involving complex changes to your landing page is to use “Edit HTML” feature. Instead of relying on Optimizely’s drag-and-drop functionality, <strong>write your own HTML code for the block that you want to change</strong> and then use “Edit HTML” to paste it into the experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsfhDVETK9Wfqmezr9M-UQ.png" /></figure><p>In the example above, I could write my own code for the header of my Medium blog, and replace the original with “Edit HTML”.</p><p>Why? Because then you are in total control of how this block will look and behave in the experiment, and moreover, this change would be executed through a single JQuery command.</p><blockquote>Hint: you can always check how Optimizely executes the changes by expanding &lt;edit code&gt; section in the right bottom.</blockquote><h4>Hide, style, edit elements with CSS</h4><p>An alternative to replacing HTML code of a block is to <strong>create experiment using pure CSS styling</strong>. For instance, if you want to understand if hiding menus and links on a landing page results in the better conversion, you can hide all unneeded page elements with something like:</p><blockquote>&lt;style&gt; #menu { display: none; }<br>#footer-links { display: none; }<br>&lt;/style&gt;</blockquote><p>or if you want to change color and size of the “Sign up now” button, you can also do it with pure CSS (obviously, you need to use your own CSS selectors):</p><blockquote>&lt;style&gt;<br>#sign-up-botton {<br>background-color: #003399;<br>width: 200px;<br>height: 50px;<br>}<br>&lt;/style&gt;</blockquote><p>If you can create a test variation with pure CSS, everything that’s left is to select <em>any element </em>in Optimizely interface (I usually select the smallest static element in the header) and paste your CSS code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QHtcS_gT97jxrj-GiGSuA.png" /></figure><p>When you click “Done”, your experiment will include custom changes.</p><h4>Not enough? JQuery should help!</h4><p>If you can live with the above options that’s great, but in case you need more, you can always <strong>write your own JQuery code to create a landing page variation</strong>!</p><p>Remember that &lt;edit code&gt; button in the bottom right? Yeap, that exactly what we need to add our own JQuery code, just expand it and the sky will be your only limit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_4Ihxb8do1lgJkoQk50FA.png" /></figure><p>As you can see, two lines of JQuery made my avatar bigger:</p><blockquote>$(“.hero-avatar”).attr(“style”,”width:200px;height:200px;”);<br>$(“.avatar”).attr(“style”,”width:200px;height:200px;”);</blockquote><p>Obviously, you don’t need to go into JQuery writing to do such simple things, but who knows what things you might want to test on your landing page. What if you have a button on your website that submits a form and you’d love to show an alert when someone clicks it (to test if warning on form submit causes a drop on conversion)? Jquery would be the only option in that case.</p><p>To illustrate, let’s show an alert when someone clicks on “Follow” on my Medium blog:</p><blockquote>$( “.button—follow” ).click(function() { alert(“Are you sure you want to follow this dude?”);<br>});</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*gkf657hb62dpQF6EpMlUdw.png" /></figure><p>That works and illustrates that <strong>with JQuery you can change not only the look and feel of the landing page, but the whole interaction with the user</strong>.</p><p>Hope this helps you run some nice experiments. <strong>As always, feel free to ping me on Twitter (</strong><a href="https://twitter.com/jevgenijs"><strong>@jevgenijs</strong></a><strong>) if you have any questions!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec8019535da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 cool things you can do with Google Tag Manager]]></title>
            <link>https://medium.com/@jev/10-cool-things-you-can-do-with-google-tag-manager-7f1d59d794f5?source=rss-8e7b507d5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f1d59d794f5</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[google-tag-manager]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[google-analytics]]></category>
            <dc:creator><![CDATA[Jevgenijs Kazanins]]></dc:creator>
            <pubDate>Tue, 02 Sep 2014 06:05:01 GMT</pubDate>
            <atom:updated>2017-03-05T07:45:01.974Z</atom:updated>
            <content:encoded><![CDATA[<h4>to manage and track your website better</h4><p><a href="https://www.google.com/tagmanager/">Google Tag Manager</a> is a free service that allows easy injection of tags on websites. In simple words, Tag Manager helps you fire JavaScript code, such as Google Analytics tracking code on your website or specific sections of your website.</p><p>I started using Google Tag Manager a year ago and since then became probably it’s biggest fan on Earth, as it allows enhancing your analytics setup and provides an easy way to introduce changes to your website.</p><p>Tag Manager allows you to do so many things, and this article is an attempt to help you get started with a few. To fully benefit from the article you need to grasp a few concept behing Google Tag Manager:</p><blockquote><strong>Tag Container</strong>: a collection of tags that are defined in Google Taga Manager and are fired on your website</blockquote><blockquote><strong>Tag</strong>: a single script that is fired based on a rule (i.e. fire AdWords Conversion Tag when a visitor registers on the website)</blockquote><blockquote><strong>Rule</strong>: a URL-based or event-based rule that causes the tag to fire (i.e. user submits registration form)</blockquote><blockquote><strong>Macro</strong>: a variable, either predefined or collected from an element or code on the website, that can be used in defining the rules (i.e. page URL or HTML form id)</blockquote><p>Let’s get started:</p><h3>1. Add all tracking scripts you need without the help from engineers</h3><p>The most obvious benefit of using Google Tag Manager is the ability to publish all tracking scripts without involving your engineers (just make sure you don’t break the website).</p><p>If you have Google Tag Manager installed on your website you can easily adjust and publish Google Analytics, Piwik, Kissmetrics, Optimizely, Hubspot or whatever other tracking scripts you use.</p><p>Tag Manager has a predefined tag for inserting Google Analytics or Universal Analytics tracking codes, but you can always use Custom HTML tag to add tracking codes for other tools:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*cjP5dy6kF2fwzOawIggcfA.png" /></figure><p>When setting up Google Analytics or similar tracking scripts make sure you add “All pages” to the Firing Rules for the script to run on all pages of your website.</p><h3>2. Set up Google Analytics goal tracking</h3><p>It is super easy to set up event-based Google Analytics goals. Using Tag Manager you fire a Google Analytics event when a certain event is happening (i.e. a visitor reached Registration Page) and then use this event to set up event-based goal in Google Analytics.</p><p>Start by creating a Google Analytics Tag in Tag Manager:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*G_MXPJfOWtOJwlMibi9Aog.png" /></figure><p>Insert the Tracking ID (Google Analytics profile ID, UA-XXXXXX), chose Tracking Type “Event” and fill in the Category, Action and Label names for the event you want to track:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*YZoHWwRMLe1Psk7masUIUA.png" /></figure><p>In this example, Tag Manager will fire a Google Analytics event with the Category “user-flow” and Action “registration-page-visit”.</p><p>The only thing left, is to define the Firing Rules for this event to fire when a user visits “Registration Page” (assuming the URL of the “Registration Page” is something like <em>www.greatwebsite.com/register</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*I5hXbWXwiyA01YX9FR4pnA.png" /></figure><p>Save and publish Google Tag Manager container, and let’s set up the event-based goal in Google Analytics by chosing “Goals” under the view section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*aqGgXJ8plEP-SJBsIwDeaQ.png" /></figure><p>Chose “Custom” at the first step of goal set up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*zvQPsS2zQ41Z_EYvqk_8Vw.png" /></figure><p>Type in the goal name and chose type “Event”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*NxtABFZFuekDmEBt1QpPWQ.png" /></figure><p>Type in the Category and Action names that you used when setting up the Tag Manager event:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*AVGaSYK4Qyw7Pk7Wm2bHPw.png" /></figure><p>That’s it! Every time someone visits the “Registration Page”, Tag Manager will fire a Google Analytics event and Google Analytics will register goal conversion based on this event.</p><h3>3. Fire AdWords Conversion Tag to measure conversions from SEM campaigns</h3><p>If you use AdWords in your marketing mix, then you might be interested in tracking conversions this channel generates. Setting up AdWords Conversion Tag is extremely easy and come with a predefined tag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*RB-PbJGayOblo3tHdiH7Vg.png" /></figure><p>Add Conversion ID and Conversion Label for the AdWords conversion that you want to track (you can find both under Tools -&gt; Conversions). You can also add Conversion Value, but it is optional:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*8fk76XdNSrjyJvy4Kih_Mw.png" /></figure><p>Finally, define the Firing Rule for the AdWords Conversion Tag to fire:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*PXMrx69MSZvVhzCFNBSgaw.png" /></figure><p>The above example assumed that after a user registers on the website, he or she is redirected to the URL <a href="http://www.greatwebsite.com/welcome,"><em>www.greatwebsite.com/welcome</em></a><em>; </em>however, you can read further to learn how to set up a rule when there is no such “Welcome” page (hint: fire the tag on user registration form submission).</p><h3>4. Fire AdWords Remarketing Tag to collect remarketing lists</h3><p>You can also use a predefined tag to fire AdWords Remarketing Tag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*nxoPB_tGXPTVpfm5r-tG2A.png" /></figure><p>To complete the setup you need to find the Conversion ID (under your AdWords account navigate to Campaigns -&gt; Shared Library -&gt; Audience and find the conversion id for All visitors tag).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*XJGIGiR1gNR_ylkqyFntgg.png" /></figure><p>Define Firing Rules as “All pages” for the remarketing tag to collect the list of all visitors to your website. Save and publish.</p><h3>5. Style your website with CSS</h3><p>Sometimes you need to style or hide a particular element on your website (i.e. the regulator issued a new rule regulating the minimum font size of the financial warning). If your CMS allows it’s great, but there might be cases where you urgently need to do it and the engineers are not available or you just can’t wait for the next release cycle.</p><p>In this case, Google Tag manager offers a <a href="https://support.google.com/tagmanager/answer/3281386?hl=en">Custom HTML</a> tag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*XjuLgiUjmrWBuT8384nVqA.png" /></figure><p>Just wrap your CSS with &lt;style&gt;&lt;/style&gt; and set up the correct Firing Rules. Please also try to implement the change using a more permanent option; style your website with Tag Manager is great, but it has it’s limitations.</p><h3>6. Style your website with JavaScript</h3><p>What if CSS alone is not enough and you need to add extra text of elements to the webpage (and the engineers are still not available)? That’s easy with the same <a href="https://support.google.com/tagmanager/answer/3281386?hl=en">Custom HTML</a> tag and some knowledge of JavaScript or JQuery.</p><p>Add a new Custom HTML tag, write your JavaScript code (don’t forget to wrap it with &lt;script&gt;&lt;/script&gt; and set up the Firing Rules.</p><p>Use .append(), .before() and .after() for adding block of HTML. For instance, if you need to add a warning before your website’s footer you could use the following:</p><blockquote>&lt;script&gt; $( “#footer” ).before( “&lt;h3&gt;Warning before website’s footer&lt;/h3&gt;” );<br>&lt;/script&gt;</blockquote><p>Using a combination of CSS and JQuery you have very few limits of the ways you can adjust your website!</p><h3>7. Track button clicks</h3><p>On particular occassions you might be interested in tracking button clicks on specific pages. For instance, you added a “Share on Twitter” button and would like to track the number of times people clicked on it.</p><p>In order to track the clicks of this button using Tag Manager we need to set up <a href="https://support.google.com/analytics/answer/1033068?hl=en">Google Analytics event</a> firing (essentially, every time someone clicks “Share on Twitter” button, a Google Analytics event is fired). At first, create a Click Listener tag and fire it either on All Pages or on a specific page (use Firing Rules to control on which pages the clicks are tracked).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ew7mSNS4J-bv6_kDUGnY2Q.png" /></figure><p>Now you need to add a Google Analytics tag (chose either Universal Analytics or Classic Google Analytics depending on which version of Google Analytics you are using) to fire an event that will be fired each time the “Share on Twitter” button is clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*v4iPNVv7fqNAWHI8qCIXEw.png" /></figure><p>Insert the Tracking ID of your Google Analytics profile, change the Track Type to “Event” and enter Category, Event and Action names for the event (use naming convension that suits your taste):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*IhsZ8AnIpAIIu6cx49cDXg.png" /></figure><p>In the example above, every time “Share on Twitter” button is clicked an event with Category “button-clicks” and Action “share-on-twitter-button-click” will be fired.</p><p>Finally, you need to set up Firing Rules for this Google Analytics tag (we want it to be fired only when the “Share on Twitter” button is clicked):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nv4hKWyeEbWAnO7L5ik7iA.png" /></figure><p>In the example above the Firing Rule has two rules: 1) there is a gtm.click event is fired (this is fired by the Click Listener tag that we set up earlier), and 2) when the {{element id}} (or the id of the HTML element which was clicked) equals “shareontwitterbutton” (this assumes that “Share on Twitter” button has id=”shareontwitterbutton”, but you can adjust this value to reflect your website).</p><p>That’s it, now you can see clicks on the “Share on Twitter” button in Google Analytics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*YZ2wAG0aKY1bMyj0raY8-g.png" /></figure><h3>8. Track file downloads</h3><p>In case you want to track file downloads off your website (i.e. downloads of the media kit from “About Us” page). Similarly to button click tracking you need to fire a Google Analytics event firing using Tag Manager.</p><p>Follow the steps from “Track Button Clicks” to create a “Link Click Listener” tag (make sure you chose “Link Click Listener” not “Click Listener” when setting up the tag).</p><p>Again, add a Google Analytics tag with Track type of “Event” and chose the names for Category, Action and Label (you can name as the way you prefer):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*8Xu-0imoN8ztPKlX28RyhA.png" /></figure><p>And set up the Firing Rules to track click on the Media Kit downloan URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*EO6ce0KhZ7oQw_Riocb5Zw.png" /></figure><p>As you can see from the above, the Google Analytics event will be fired when: 1) Link Click Listener captures a link click (gtm.linkClick event), and 2) the link URL includes media-kit.pdf (this assumes that you link to the Media Kit using <em>&lt;a hreg=”/download/</em><strong><em>media-kit.pdf</em></strong><em>”&gt;Download Media Kit&lt;/a&gt;</em>).</p><p>That’s it, every time someone click on the Media Kit download link a Google Analytics event fill be fired (another reason to check Real-Time section of your GA).</p><h3>9. Track form submissions</h3><p>On some occassions, you want to track a specific action, such as user registration, but Google Analytics’ URL based goals are not an option (i.e. you don’t have a dedicated “Thank you for registration” page). In this case you can use Form Listener tag and create events when a specific form is submitted.</p><p>Similarly to button click and file download tracking you first create a listener. Chose Form Submit Listener this time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ftb7kJBW9RmoG3vbqDQRfg.png" /></figure><p>Next, create a Google Analytics tag, choose Track type “Event” and fill in the Category, Action and Label of your choice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*o0SviHHmLj_4VW7OHoXQLg.png" /></figure><p>Finally, set up the Firing Rules for the Google Analytics event to fire when User registration form is submitted (assuming this form has id “user-registration-form”):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Z8I5ZnQJ0Ro_eKcj0SMm3Q.png" /></figure><p>Save, Publish Tag Manager container and check if this tag is fired correctly using Google Analytics Real-Time section.</p><h3>10. Track JavaScript errors</h3><p>Finally, you might be interested in tracking JavaScript errors on your page (i.e. failing affiliates tracking script). Again, you will need to set up a listener tag and fire and event when this listener tag captures a Javascript error.</p><p>Let’s first set up, the JavaScript Error Listener Tag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*EoAOGu7leCYIcAvjYLthug.png" /></figure><p>We also need to create Macro for capturing JavaScript error message and another Macro for capturing the URL on which the error occured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*41a_okOS2oMmDjqw4sscTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*S-0aV9BYEsUjD1eupdpkJQ.png" /></figure><p>Now let’s create a tag that will fire a Google Analytics event and pass the error message and error url:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*PJbGIQQf_F55ZsE90Qd3jw.png" /></figure><p>and fire it when JavaScript Error Listener captures an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*y8ys078orihVKrB9qi3O4g.png" /></figure><p>That’s it, just don’t forget to check your Google Analytics regularly for JavaScript Error events.</p><p>Hope this was helpful and don’t forget to Publish your Tag Manager Container!</p><p><strong>Feel free to ping me on Twitter if you have any questions or need help with using Google Tag Manager: </strong><a href="https://twitter.com/jevgenijs"><strong>@jevgenijs</strong></a></p><h4>Check out my other blog posts:</h4><ul><li><a href="https://medium.com/p/62ae3ed74667"></a></li><li><a href="https://medium.com/p/bc5a43537e23"></a></li><li><a href="https://medium.com/p/ec8019535da"></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f1d59d794f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>