HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Google Analytics tracking for HTML 5 video player

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
trackinggoogleplayervideoforhtmlanalytics

Problem

The jQuery code is for html5 video event GA tracking and I want to make it a little bit more shorter and cleaner. The code works: I am getting all the events, but would like to make it more simple.

function videoEnd() {
    console.log("Finished");
    ga('send', 'event', 'Videos', 'Finished', 'omegavideo');
}
$(document).ready(function() {
    var a = 0;
    var b = 0;
    var c = 0;
    var j = 0;

    /* Video Watched */
    $("#videoplayer").bind("timeupdate", function() {
        var currentTime = this.currentTime;
        if (currentTime > 0.25 * (this.duration)) {
            if (i  0.50 * (this.duration)) {
            if (w  0.75 * (this.duration)) {
            if (z < 1) {
                console.log("watched 75%");
                ga('send', 'event', 'Videos', 'Watched 75%', 'Video 1');
            }
            c = c + 1;
        }
    });

    /* Video Finished, Thanks */
    $("#videoplayer").bind("ended", function() {
        if (j < 1) {
            console.log("Finished 100%");
            ga('send', 'event', 'Videos', 'Finished 100%', 'Video 1');
        }
        j = j + 1;
    });

})

Solution

I would use a single bind:

$("#videoplayer").bind("timeupdate", function() {
    var currentTime = this.currentTime;
    if (currentTime > 0.75 * (this.duration)) {
        a = a + 1;
        console.log("watched 75%");
        ga('send', 'event', 'Videos', 'Watched 25%', 'Video 1');
    } else if (currentTime > 0.50 * (this.duration)) {
        b = b + 1;
        console.log("watched 50%");
        ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
    } else if (currentTime > 0.25 * (this.duration)) {
        c = c + 1;
        console.log("watched 25%");
        ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
    }
});


Unless there's a specific reason for you not to?

Code Snippets

$("#videoplayer").bind("timeupdate", function() {
    var currentTime = this.currentTime;
    if (currentTime > 0.75 * (this.duration)) {
        a = a + 1;
        console.log("watched 75%");
        ga('send', 'event', 'Videos', 'Watched 25%', 'Video 1');
    } else if (currentTime > 0.50 * (this.duration)) {
        b = b + 1;
        console.log("watched 50%");
        ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
    } else if (currentTime > 0.25 * (this.duration)) {
        c = c + 1;
        console.log("watched 25%");
        ga('send', 'event', 'Videos', 'Watched 50%', 'Video 1');
    }
});

Context

StackExchange Code Review Q#134828, answer score: 3

Revisions (0)

No revisions yet.