Google Tag Manager(GTM) trigger Click Element contains 작동하게 하기

박정기·2023년 1월 5일
0

google-analytics

목록 보기
1/1
post-thumbnail

Google Tag Manager의 trigger filter를 기본 제공 변수인 Click Element와 contains로 적용하면 제대로 작동하지 않는 문제를 해결하기 위한 글입니다.

구글 태그매니저를 이용할 때 변수 중 Click Element를 이용해야 할 때가 있다. 그런데 해당 변수는 contains trigger가 작동하지 않는다..

나 같은 경우에는 특정 element click 이벤트를 수집해야 했는데, 해당 element 내의 자식 element 위치를 클릭하면 onClick함수는 정상적으로 실행되지만 자식 element가 클릭된 걸로 인식돼 trigger를 equals triggerClick Classes 변수를 이용해 처리할 수가 없었다.

그래도 어차피 자식 element의 Click Element 변수에 parent element가 포함되니까 contains를 쓰면 될 거라고 생각했지만, 계속 제대로 작동하지 않아 구글링해보니 원래 작동하지 않는다고 한다...
해결하기 위해 모든 자식 element에 pointer-events: none을 추가해 자식 element click이 인식되지 않게 하는 방법도 있지만, 너무 귀찮고 좋은 방법이 아닌 것 같아서.!

Custom javascript로 Click Element와 같은 값을 리턴하는 커스텀 변수를 만드는 법을 찾아서 사용했다. (출처)

function() {
  // Build a CSS path for the clicked element
  var originalEl = {{Click Element}};
  var el = originalEl;
  if (el instanceof Node) {
    // Build the list of elements along the path
    var elList = [];
    do {
      if (el instanceof Element) {
        var classString = el.classList ? [].slice.call(el.classList).join('.') : '';
        var elementName = (el.tagName ? el.tagName.toLowerCase() : '') + 
            (classString ? '.' + classString : '') + 
            (el.id ? '#' + el.id : '');
        if (elementName) elList.unshift(elementName);
      }
      el = el.parentNode
    } while (el != null);
    // Get the stringified element object name
    var objString = originalEl.toString().match(/\[object (\w+)\]/);
    var elementType = objString ? objString[1] : originalEl.toString();
    var cssString = elList.join(' > ');
    // Return the CSS path as a string, prefixed with the element object name
    return cssString ? elementType + ': ' + cssString : elementType;
  }
}

를 custom javascript 안에 넣고 변수를 생성하면 기존 Click Element와 같은 값을 리턴하면서 contains가 작동하게 할 수 있다!

profile
오르카스튜디오 공동창업자 겸 개발자입니다. team.orcar.kr

0개의 댓글