Trivial jQuery Replacement

Simplified cutdown copy of jQuery with example, intended as example for blog post.

by Keith Henry

HTML

<div id="one">
    Click in the box
</div>

CSS

#one {
    background-color: #55E;
    color: #fff;
    font-family: sans-serif;
    width: 300px;
    height: 300px;
    padding: 30px;
    position: relative;
    cursor: copy;
}

.two {
    position: absolute;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    transform: translate(-50%, -50%);
    background-color: #ed0;
    cursor: pointer;
}

JavaScript

function $(selector, context) {
    // If passed a function
    if (typeof selector === 'function') {
        if (document.readyState === 'complete')
        	// DOM content already loaded, fire once the current script block has finished
            window.setTimeout(selector);
        else
        	// Listen for the content loaded event
            document.addEventListener('DOMContentLoaded', selector);

        return;
    }

    // Assume typeof selector === 'string'
    if (selector.indexOf('<') === 0) {
        // We'be been passed an HTML string, parse it as DOM content
        var outer = document.createElement('div');
        outer.innerHTML = selector;
        return outer.children.length === 1 ? outer.children[0] : outer.children;
    }

    // We have a selector, optionally apply the context
    var result = (context || document).querySelectorAll(selector);
    return result || result.length === 1 ? result[0] : result;
}

// Example Loader, just like jQuery
$(function() {
    // Use `addEventListener` instead of `on`
    $('#one').addEventListener('click', function(e) {
        // No need for $ prefix, we always have native DOM elements
        var parent = this;

        // Create the point jQuery style
        var point = $('<div class="two"></div>');
        point.style.top = e.offsetY + 'px';
        point.style.left = e.offsetX + 'px';
        
        // Click on a point to remove it
        point.addEventListener('click', function handler(evt) {
            evt.stopPropagation();
            parent.removeChild(this);
            
            // Tidy up event in IE friendly way
            evt.currentTarget.removeEventListener(evt.type, handler);
        });

		// Add the point to the parent box
        parent.appendChild(point);
    });
});