JSFiddle - React, Tailwind, and code Playground

by rity

HTML

<div id="playerElement"></div>
<button id="incHSize">Inc H Size</button>
<button id="incVSize">Inc V Size</button>

CSS

#playerElement {
    width:20px;
    height:20px;
    background:yellow;
}
html, body {
    height:100%;
}

JavaScript

(function ($) {
    $.Player = function (element) { //renamed arg for readability

        //stores the passed element as a property of the created instance. so we can access it later
        this.element = (element instanceof $) ? element : $(element);
        //instanceof is an extremely simple method to handle passed jQuery objects,
        //DOM elements and selector strings. This one doesn't check if the passed element is valid
        //nor if a passed selector string matches any elements.
    };

    //assigning an object literal to the prototype is a shorter syntax
    //than assigning one property at a time
    $.Player.prototype = {
        InitEvents: function () {
            //`this` references the created instance object inside an instace's method,
            //however `this` is set to reference a DOM element inside jQuery event handler functions' scope.
            //So we take advantage of JS's lexical scope and assign the `this` reference to
            //another variable that we can access inside the jQuery handlers
            var that = this;
            //I'm using `document` instead of `this` so it will catch arrow keys
            //on the whole document and not just when the element is focused.
            //Also, Firefox doesn't fire the keypress event for non-printable characters
            //so we use a keydown handler
            $(document).keydown(function (e) {
                var key = e.which;
                if (key == 39) {
                    that.moveRight();
                } else if (key == 37) {
                    that.moveLeft();
                } else if (key == 38) {
                    that.moveTop();
                } else if (key == 40) {
                    that.moveBottom();
                }
            });
            
            this.element.click(function() {
  						alert( "Handler for .click() called." );
						});
            
            $(document).on('click', 'button#incHSize', function(){
           ...