Kellen Lester Kellen Lester -4 years ago 122
jQuery Question

JQuery function on background click - GTM

I have a custom tag built in GTM (Google Tag Manager). I want the tag to track when user closes a particular bootstrap modal. In order to do that, I built a custom function:

$(function () {
$('#popup').click(function() {
var label = $("#popup .container h4").text();
dataLayer.push({
'event': 'GAEvent',
'eventCat': 'Event Engagement',
'eventAction': label + " Modal - Close",
'eventLabel': label,
'gaNonInt': false
});
});
});


The HTML structure for the modal is as follows:

<div id="popup"> <!--The modal background/overlay is set here-->
<div id="popup-block">Content nested here</div>
</div>


When a user clicks on the background layer(#popup's background), the modal closes. However, when I target #popup with my custom function, the tag fires when any element nested inside the #popup div is clicked. Is there a way to target only the background of the #popup div element? Thanks in advance.

Answer Source

Try this:

$(function () {
      $('#popup').click(function(e) {
      if(e.target != this) return; // probably a child was clicked.
      var label = $("#popup .container h4").text();
      dataLayer.push({
         'event': 'GAEvent', 
         'eventCat': 'Event Engagement', 
         'eventAction': label + " Modal - Close", 
         'eventLabel': label,
         'gaNonInt': false
      });
   });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download