4
\$\begingroup\$

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 < 1) {
                console.log("watched 25%");
                ga('send', 'event', 'Videos', 'Watched 25%', 'Video     1');
            }
            a = a + 1;
        }
    });

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

    $("#videoplayer").bind("timeupdate", function() {
        var currentTime = this.currentTime;
        if (currentTime > 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;
    });

})
\$\endgroup\$
1
3
\$\begingroup\$

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?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.