0

I would like to add my Google Analytics tracking event code inline to my input html tag :

<input class="addtobag">

to have something

<input class="addtobag" onClick="_gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);">

I'm asking this as I don't have access to the file that contains the tag so I'm unable to make the change manually so I'm looking for a javascript code that I will put in the head so when that page load, the tracking event code would be injected automatically.

I want the call to be by my input class and not by id.

j0k
  • 22,600
  • 28
  • 79
  • 90

2 Answers2

2

Why do you want to do it inline?

document.getElementById('ctl00_mainContentPlaceHolder_lvLookProducts_ctrl0_buyArea3493_btnAddToCart').onclick = function () {
    _gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);
};

To do it by class name, you'll need to do a little more logic:

var inputs = document.getElementsByClassName('AddToBag'),
    i = inputs.length;

while(i--) {
    inputs[i].onclick = function () {
        _gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);
    }; 
}

Fetching by class name returns a list, so you'll have to loop through to apply the handler.

Evan Davis
  • 35,493
  • 6
  • 50
  • 57
  • I'm open to any any better alternative you may show me. Thanks –  Mar 05 '13 at 16:11
  • Ok can I use the class "AddToBag" for the getElementById instead of using ct100_mainCont.... ?? –  Mar 05 '13 at 16:29
  • because the website is generating an ID dynamically for each , using the class(addtobag) would be better as it is static –  Mar 05 '13 at 16:33
  • Thanks a million! I'm going to test this out and will update you. –  Mar 05 '13 at 18:52
  • Hi again, I need your help with a very similar question, instead of onclick I would like to set it up using onBlur and onChange. onBlur if the value is not blank inject : _gaq.push(['_trackPageview', '/vpv/FirstName.aspx']); or onChange(a slect field) inject .... –  Mar 06 '13 at 21:37
  • works the same way. What have you tried? Also, you should ask a new question rather than piggybacking on an existing one. – Evan Davis Mar 06 '13 at 21:47
  • I tried to do it using your code just by changing "click" by "blur" or "change" but it didn't work, I have created a new question here [link](http://stackoverflow.com/questions/15258968/javascript-inject-inline-code-to-a-html-tag) –  Mar 06 '13 at 22:03
-1

jQuery is your friend.

How to replace innerHTML of a div using jQuery?

$("#regTitle").html("Hello World");

EDIT

Guess I didn't read this one, but still same principle.

$(".addtobag").click(_gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']));

http://api.jquery.com/click/

Community
  • 1
  • 1
Dan
  • 1,179
  • 2
  • 10
  • 18