Reputation: 11830
So I have been asked to add/report analytics event on almost every onclick event on the site.
I haven't done analytics before but the way I was suggested was to create a common data set for each event and fire the analytics event during on click action. Meaning I will have to modify every onclick function (or this is what I was able to comprehend
I was thinking about creating a script which goes through all element, see if the element have onClick event, listen to those onclick event and then when an action like click happens, they report it
This question on SF was similar get all elements with onclick in them? but for React, onclick event are coming out to be null? (i.e the code snippet is returning empty array).
My question is similar to the above one but specific to React. In a React app how can I get all elements with onclick event?
Upvotes: 1
Views: 1381
Reputation: 1456
Simpe explanation: When the HTML page is loaded I get all the buttons in my page as an HTMLCollection
and check whether each one has an OnClick
event or not.
In my case only two buttons (the first and the third ones). You can change the tag name to whatever you want to inspect.
window.addEventListener('DOMContentLoaded', (event) => {
let buttonsCollection = document.getElementsByTagName("BUTTON");
let buttonsWithEvents = [];
for(let i = 0; i < buttonsCollection.length; i++) {
if(buttonsCollection.item(i).onclick !== null)
buttonsWithEvents.push(buttonsCollection.item(i));
}
console.log(buttonsWithEvents);
});
function add() {console.log('add');}
function sub() {console.log('sub');}
function MyButtons(props) {
return (
<div>
<button onClick = {add}>First</button>
<button>Second</button>
<button onClick = {sub}>Third</button>
</div>
);
}
Console output (as expected):
These two buttons only with the onClick
event, When you open each one in the console you'll find all the details you want about it (text, events, etc..)
Upvotes: 1