0

I would like to parse all of the HTML within a document and if there is a link to a PDF, add an onClick event.

Example:

<a href="/files/report.pdf">Report</a>

Becomes:

<a href="/files/report.pdf" onclick="javascript: _gaq.push(['_trackPageview', '/files/report.pdf']);">Report</a>

The following code works in Chrome/Firefox but not on IE9:

function AddGaqPush()
    {
        var links = document.getElementsByTagName("a");

        for (var i=0; i < links.length; i++)
        {
            if (links[i].href.indexOf(".pdf") !== -1)
            {
                links[i].setAttribute("onclick", "javascript: _gaq.push(['_trackPageview', '" + links[i].href + "']);");
            }
        }
    }

Edited to add: IE settings: Browser Mode: IE9; Document Mode: IE9 Standards

Charles Wesley
  • 828
  • 12
  • 27

3 Answers3

4

Use jQuery and you won't be limited by the browser (especially IE)

$('a[href~=.pdf]').click(function(e) {
    // your click action
    // e is a jQuery event
    // your <a> element is the variable this
});
3

Instead of adding an attribute, attach an event handler

if (links[i].attachEvent){
    links[i].attachEvent('onclick', tpv);
}
else{
    links[i].addEventListener('click', tpv);
}
function tpv(){
    _gaq.push(['_trackPageview', '" + this.href + "']);
}
Musa
  • 96,336
  • 17
  • 118
  • 137
2

The jQuery statement to accomplish this would look like:

$('a[href*=".pdf"]').click(function(e) {
    _gaq.push(['_trackPageview', $(this).attr('href')]);
});

I liked Nannuo Lei's answer to this question but the solution wasn't quite accurate/complete and I don't yet have sufficient reputation to comment on that post.

You will want quotes around the string you are searching for and the *= selector allows you to identify a substring of a larger string, not just a word separated by whitespace as the ~= selector will accomplish. More detail on jQuery selectors can be found here: https://api.jquery.com/category/selectors/

zerodega
  • 21
  • 1