#GTMTips: Get the center pointer of the visual element – News Couple
ANALYTICS

#GTMTips: Get the center pointer of the visual element


Time for a super simple article #GTMTips (I know, I always write these are simple tips, but then they spiral into complex giants). Today, we are going to cover a cool trick that you can use with the Element Visibility launcher in Google Tag Manager. This tip was inspired by a question from Eugen Potlog in the Google Tag Manager group on Facebook.

The use case is that you have an Element Visibility launch launch of a number of elements that all share the same CSS selector. In the image below, I want to turn on the visibility trigger when it is present <h2> The header element becomes visible on the screen. However, I also want to know which one of all these heads triggered the trigger. In other words, I want a file Location From the head If this is the fifth header from the top, I want to get the number 5 To use in my tags. If this is the first title, I want it back 1.

It’s very easy to do with a custom JavaScript variable, and below I’ll show you how to do it.


X


Simmer . Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava right in your inbox!

Tip 84: Get the index of the position of the visible element

Here’s what a custom JavaScript variable should look like:

function() 
  var list = document.querySelectorAll('h2'), // Make sure this CSS selector matches the one in the trigger
      el   = Click Element;
  return [].indexOf.call(list, el) + 1;

This takes advantage of something you may not have thought of before, which is the reality of the endogenous variable Click Element Returns the element that caused the Element Visibility trigger to fire. It is a multipurpose variable in this sense.

The script first creates a list of all the possible elements that the Element Visibility launcher can shoot, so this is important Argument delimiter of document.querySelectorAll(selector) Matches the one you’re using in the Element Visibility launcher. Once the list is created, indexOf() It is used against a native array object (because the list returned by querySelectorAll he does not have .indexOf() ), and checks if the list contains the element that launched the trigger.

If the list contains it, the position of the element will be returned as a positive integer, so it will be the first element on the page 1, and the second will be 2 and so on and so on. If the element does not match the list of elements in the variable list, Location 0 is returned. This means that you have misconfigured the delimiter(s).

This was a simple tip, no doubt, but I hope it will be useful to some of you!



Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button