Reputation: 27
I am logging click events on my website to Google Analytics. The way I do on buttons clicked is this:
document.getElementById("loginButton").addEventListener("click", function() {
ga('send', 'event', 'Login Button', 'clicked');
}, false);
I also would like to log the tabs clicked on a FAQ I have on a <p:accordionPanel>
element, from PrimeFaces. Code follows:
<p:accordionPanel id="helpAccordion" value="#{indexFAQController.helperBean}" var="bean" multiple="false" >
<p:ajax event="tabChange" listener="#{indexFAQController.onTabChange}" />
<p:tab id="helpTab" title="#{bean.title}">
#{bean.message}
</p:tab>
</p:accordionPanel>
The way the ids are generated on the view is dynamic. Every accordion tab is composed of a <h3>
and a <div>
with the dynamic ID of helpAccordion:n:helpTab, where n is the auto-generated tab number, starting from 0. Code:
<div id="helpAccordion" class="ui-accordion ui-widget ui-helper-reset ui-hidden-container" role="tablist" data-widget="widget_helpAccordion">
<h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-state-active ui-corner-top" role="tab" aria-expanded="true" aria-selected="true" tabindex="0"><span class="ui-icon ui-icon-triangle-1-s"></span>TAB TITLE 0</h3>
<div id="helpAccordion:0:helpTab" class="ui-accordion-content ui-helper-reset ui-widget-content" role="tabpanel" aria-hidden="false">
TAB TEXT 0.
</div>
<h3 class="ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" role="tab" aria-expanded="false" aria-selected="false" tabindex="0"><span class="ui-icon ui-icon-triangle-1-e"></span>TAB TITLE 1</h3>
<div id="helpAccordion:1:helpTab" class="ui-accordion-content ui-helper-reset ui-widget-content ui-helper-hidden" role="tabpanel" aria-hidden="true">
TAB TEXT 1.
</div>
<input type="hidden" id="helpAccordion_active" name="helpAccordion_active" value="0" autocomplete="off">
</div>
So I need a way to get which tab was clicked and get the beginning inner text of it (if possible, the title in the corresponding <h3>
would be even better) of it for it to be passed to the Google Analytics function.
Any help?
Thank you.
Upvotes: 0
Views: 204
Reputation: 3038
Why not have one listener at the top of the page (body). The listener gets the event, and is able to figure out what element originated the click-event. Maybe you would have some specific data-attribute on each element that you care about.
For example:
<p:accordionPanel data-send-to-google="whatever">Accordion panel!</p>
function theHandler(ev) {
if (ev.target.hasAttribute("data-send-to-google")) {
const theData = ev.target.getAttribute("data-send-to-google");
ga('send', 'event', theData, 'clicked');
}
}
document.querySelector("body").addEventListener("click", theHandler);
Upvotes: 1