I have a website where there are three different modal buttons and I wrote a variable to get the values in a data layer which is working good but when I first click on the button I get 2 events and it starts doubling up for each click afterwards.
Here is my code
function() {
if ({{Click Text}} == 'STUDY DESIGN'){
$(this).each(function() {
$(this).on("click", function(){
var imageText = $({{Click Element}}).closest('.d-md-flex').find('.image-wrapper img.image__desktop').attr("alt");
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'studyDesignInteraction',
'action': imageText
});
});
});
return true;
}
}
The first click comes back with two events and it keeps doubling up after each event. How can I only apply to one click?
$(this) in your code is window
$(this).each(function() { console.log(Object.keys(this)[0])
$(this).on("click", function() { console.log(Object.keys(this)[0])
var imageText = $('img').closest('.d-md-flex').find('.image-wrapper img.image__desktop').attr("alt");
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'studyDesignInteraction',
'action': imageText
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="x" class="d-md-flex">
<div class="image-wrapper">
<img class="image__desktop" />
</div>
</div>