Reputation: 71
I am trying to send an event to Google Analytics when clicking on a specific button.
this is my button ID: (#data_243342)
This is my GA
script to push on clicking on the above button.
onclick="dataLayer.push({"event": "eventGA","eventCategory" : "data1","eventAction" : "data-1-click","eventLabel" : "yes"})"
How can i pass this in a jqueryor javascript?
Upvotes: 2
Views: 9136
Reputation: 5571
There are many ways to do this:
With Javascript:
(function() {
var button = document.getElementById("data_243342");
button.addEventListener("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
})();
<button id="data_243342" type="button">Send</button>
With jQuery:
$(function() {
$("#data_243342").on("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="data_243342" type="button">Send</button>
Update:
To add more button with the same function, you could try something like this:
With Javascript: By using document.getElementsByTagName
to find the buttons to bind with the function.
(function() {
onload = function() {
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
}
};
})();
<button id="data_243342" type="button">Send 1</button>
<button id="data_243343" type="button">Send 2</button>
<button id="data_243344" type="button">Send 3</button>
With jQuery: By using the #id selectors of the buttons.
$(function() {
// Set the buttons id in the jQuery function.
$("#data_243342, #data_243343, #data_243344").on("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="data_243342" type="button">Send 1</button>
<button id="data_243343" type="button">Send 2</button>
<button id="data_243344" type="button">Send 3</button>
Update:
Another way in jQuery is by using class selectors.
$(function() {
// Every button with the btn-GA class can execute the function.
$(".btn-GA").on("click", function() {
dataLayer.push({
"event": "eventGA",
"eventCategory": "data1",
"eventAction": "data-1-click",
"eventLabel": "yes"
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="data_243342" class="btn-GA" type="button">Send 1</button>
<button id="data_243343" class="btn-GA" type="button">Send 2</button>
<button id="data_243344" class="btn-GA" type="button">Send 3</button>
Hope this helps.
Upvotes: 4