Alexander C.
Alexander C.

Reputation: 1181

How can i make my jQuery function with .each() in it shorter?

My function:

    $('a[href$=".pdf"]').each(function () {
        var $linkText = $(this).text();
        $(this).attr('onclick', "_gaq.push(['_trackEvent','" + $linkText + "','click']);");
    });

    $('a[href$=".doc"]').each(function () {
        var $linkText = $(this).text();
        $(this).attr('onclick', "_gaq.push(['_trackEvent','" + $linkText + "','click']);");
    });

the parts are repetitive:

var $linkText = $(this).text();
        $(this).attr('onclick', "_gaq.push(['_trackEvent','" + $linkText + "','click']);");

How can i pull those parts into an outside function so that I'll have something like this ?:

$('a[href$=".xls"]').each(function (index, value) {            
        AddGoogleTracking(value);
    });

function AddGoogleTracking(value) {
    var $linkText = value.text();
    $(this).attr('onclick', "_gaq.push(['_trackEvent','" + $linkText + "','click']);");
}

Upvotes: 0

Views: 78

Answers (2)

Jason P
Jason P

Reputation: 27022

You could select both together:

$('a[href$=".pdf"], a[href$=".doc"]');

You can also simplify by adding the click handler directly, like this:

$('a[href$=".pdf"], a[href$=".doc"]').click(function() {
    _gaq.push(['_trackEvent', $(this).text(), 'click']);
});

It might be a good idea to simplify further by giving any link you want tracked a common class, so you can select them that way:

$('.track-link').click(...);

Upvotes: 4

zzzzBov
zzzzBov

Reputation: 179226

Don't add an [onclick] attribute, don't repeat a selector when the same function body applies to both.

Do use .on() to bind click events to the matched elements:

$('a[href$=".pdf"], a[href$=".doc"]').on('click', function () {
    window._gaq.push(['_trackEvent', $(this).text(), 'click']);
});

Upvotes: 0

Related Questions