Thursday, July 13

Creating and Styling Multiple Elements in JavaScript


A simple function to make it easy to create and style multiple html elements in JavaScript. Pass this function a JavaScript object with the settings you need create and it will return a element with all children elements created and appended.

The Function

function createAndStyle( styles ){
  var elm = document.createElement('div');
  for(var style in styles){
    let value = styles[style];
    if (typeof( value )==='object') {
      let childElm = createAndStyle( value );
      elm[style] = childElm;
    } else {
      switch (style){
        case "id": = value;           break;
        case "class":
        case "className": elm.className = value;    break;
        default:[style] = value; break;
  return elm;

The Example Code

let buttonStyle = {
        display: 'inline-block',
        width: '50px',
        height: '50px',
        background: '#777',
        marginLeft: '10px'
  , SideBar = {
      id: 'sideBar_Root',
      position: 'absolute',
      left: '0px',
      top: '1px',
      width: '298px',
      height: 'calc(100% - 4px)',
      padding: '10px',
      background: '#eee',
      border: '1px dashed #333',
      button1: buttonStyle,
      button2: buttonStyle,
      button3: buttonStyle,
      button4: buttonStyle,
      button5: buttonStyle,
      button6: buttonStyle,
      button7: buttonStyle,
      button8: buttonStyle,
      button9: buttonStyle,
      button10: buttonStyle

function init() {
  let body = document.querySelector('body')
    , elm = createAndStyle( SideBar );
  body.appendChild( elm );

window.addEventListener('load', init); Example

Dynamically Style Element from Variable ( JavaScript )


Web browsers have become more and more capable, more powerful, in the recent years. With web pages becoming more complicated and more reliant on JavaScript and CSS I find our CSS files are becoming larger and harder to keep orderly.

Lately, most of the HTML elements in any given project I program, are being created in JavaScript code. Now that the elements are being created in JavaScript, I wanted an easy way to style the elements as well. Making it easier to create more modular components, and free code from having separate CSS files.


Now with a simple function, which I pass the element variable, and a JavaScript object variable with the styles defined, I can easily change the style without having to look through the CSS files.

Settings Variable

var style = {
        position: 'absolute',
        top: '50px',
        left: '50px',
        width: '30%',
        height: '30%',
        background: '#eee',
        border: '1px dashed #333'

The Function
function styleElement( elm, styles ){
  for(var style in styles){[style] = styles[style];
  return elm;

The Example Code
var root = {
        width: '100%',
        height: '100%',
        margin: '0px',
        padding: '0px',
        overflow: 'hidden'

function init() {
  let html = document.querySelector('html')
    , body = document.querySelector('body')
    , elm = document.createElement('div')
  body.appendChild( elm );
  styleElement( html, root );
  styleElement( body, root );
  styleElement( elm, styles );

window.addEventListener('load', init); Example

See the Pen Style Element from jsObject by Failed Sleep (@FailedSleep) on CodePen.

Friday, April 14

SVGs: Cut shapes out of other shapes. Transparencies


While making a SVG graphic of an "id card" I realized I needed the top part of the card to have a transparent hole in it. Searching the internet mainly shows the "fill=odd" trick, and drawing the objects with paths. Which is ok if you want to cut a square out of a circle, or a circle out of a star. If you want to cut a rectangle with rounded corners, creating a path becomes much harder.

and then came Mask

I am not sure which article, or which blogger I first read about masks on. My initial thoughts were that it followed the same lines as the "fill=odd" trick. Then I saw a code example, and it all became clear. Mask is exactly what I was looking for.


Before I used mask, I had a rectangle with rounded corners, with the fill color set to the same as the background color.

Using the mask feature, we define the mask in the DEF section, and anything colored #FFFFFF is shown, anything #000000 is transparent.

Monday, April 10

JavaScript: Draggable DOM Element


I wanted to create a completly Vanilla JavaScript draggable DOM element tool. This will be used in a future project idea. You can watch the time lapse of this being created:

dragItem.js   (JavaScript Source Code)

(function() {
  'use strict';
  var inDrag = false
    , dragElement = null
    , dragOffsetX = 0
    , dragOffsetY = 0
    , body = document.getElementsByTagName('body')[0];
  function dragHandler( event ) {
    if (event.button != 0) return;
    dragElement =;
    var canDrag = dragElement.getAttribute('drag')
    while (!canDrag && dragElement.parentElement) {
      dragElement = dragElement.parentElement;
      canDrag = dragElement.getAttribute('drag');
    if (!canDrag) return dragElement = false;
    dragOffsetX = event.clientX - dragElement.offsetLeft;
    dragOffsetY = event.clientY - dragElement.offsetTop;
    body.appendChild(dragElement); = 'none';
    inDrag = true;
  function dragMove( event ) {
    if (!inDrag) return false; = event.clientX-dragOffsetX+'.px'; = event.clientY-dragOffsetY+'.px';
  function dragStop() {
    if (!inDrag) return;
    if (event.button != 0) return;
    inDrag = false;
    if ( (dragElement.offsetTop + dragElement.offsetHeight)<20) = 20 - dragElement.offsetHeight+'.px';
    if ( (dragElement.offsetLeft + dragElement.offsetWidth)<20) = 20 - dragElement.offsetWidth+'.px';
    if ( (dragElement.offsetTop+20)>window.innerHeight) = window.innerHeight - 20+'.px';
    if ( (dragElement.offsetLeft+20)>window.innerWidth) = window.innerWidth - 20+'.px';
    dragElement.zIndex = '10'; = '';
    dragElement = null;
  function init() {
    var dragableItems = document.querySelectorAll('[drag]')
    for (let itemID=0; itemID<dragableItems.length; itemID++) {
      let item = dragableItems[itemID];
      item.className+=' dragable';
    window.addEventListener('mousedown', dragHandler );
    window.addEventListener('mouseup', dragStop );
    window.addEventListener('mousemove', dragMove );
  window.addEventListener('load', init);

index.html   (HTML Source Code)

Check out the CodePen

See the Pen Draggable DOM Element by Failed Sleep (@FailedSleep) on CodePen.

Wednesday, April 5

Simple OBS Overlay System: NodeJS, Express, WebSockets


I have noticed after watching a number of live streams on that one of the things most starting streamers have problems with is setting up some overlays for their stream. After a number of people asked for a simple overlay system, I decided to write a simple system which anybody with even limited HTML, CSS, JavaScript capability could modify for their use.

I go through the steps of installing Open Broadcaster Software. Downloading and installing NodeJS v6.10.2. Then I continue on with programming a simple overlay system, which could be upgraded to support remote control.

Directory Sturcture
  • OBS_Overlay_System
    • public
      • images
        • 0.background.png

        • 2.streaming.png
        • 3.brb.png
        • 3.oops.png
        • 4.done.png
      • index.html
    • overlay.js
    • package.json

Source Code
var server = require('http').createServer()
  , Express = require('express')
  , app = Express()
  , port = 2017
  /* WebSocket */
  , wsServer = require('ws').Server
  , wss = new wsServer({
                          server: server

wss.broadcast = function(data) {
  wss.clients.forEach( function each(client){
    if (client.readyState === 1) {

wss.on('connection', function(socket){
  console.log('Client Connected!');
  socket.on('close', function() {
    console.log('Client Disconnected!');

app.use( function(req, res, next){
  if (req.path != '/overlay/broadcast') return next();
  var data = req.query['stage'];

app.use( Express.static( __dirname+'/public' ) );

server.on( 'request', app );

server.listen( port, function() {
  console.log('Listening on http://localhost:'+port);


  "name": "fs-obs-overlay",
  "version": "0.1.0",
  "description": "A Very Minimilistic Overlay System for use with OBS. Uses Express, WebSockets",
  "homepage": "",
  "main": "overlay.js",
  "config": {
    "port": "2017"
  "dependencies": {
    "express": "^4.15.2",
    "ws": "^2.2.3"

Install Instructions

  1. Download Source Code
  2. Extract Source Code to a Directory
  3. Open command shell
  4. Change directory to the directory the Source Code was extracted to
  5. run "npm install"
    1. This will install the node modules required in "package.json"
  6. run "node ."
    1. this will run the overlay program
    2. "Control+C" will terminate the program.

External Links

Wednesday, March 29

Hacking Game: Part 1 - Electron Setup & Initial Code


Today I started programming the beginnings of a yet unnamed hacking game. I know there have been, and will be, many fantastic games already developed in this genre. I am not expecting this game to live up to the likes of Uplink, Hacker Evolution, or Hackmud.

The one thing that might set this one apart a little is the fact that I am streaming the development on The other small thing is that I will be posting the source code, so it is available for download and experimenting with in days of the stream.


  • Created the Main Menu
  • Started the Game Intro
  • Started the main Terminal console

Build cross platform desktop apps with JavaScript, HTML, and CSS. You can download pre compiled versions for most systems at:

Screen shots

The Links

Tuesday, March 28

NodeJS, Simple Client / Server


The minimum amount of code to have NodeJS serve a simple client and server.


This code uses NodeJS module "" which you install with the following command:
npm install

Server.js Source Code

var http = require('http')
 , fs = require('fs')

 , webpage = fs.readFileSync(__dirname + '/client.html')
 , port = 2017

// Send client.html to all requests
var server = http.createServer(
 function(req, res) {
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.end( webpage );

// server listens to our app
var io = require('').listen( server );

// Send current time to all connected clients
function sendEveryone( msg ) {
 io.emit('msg', msg );

// Listen for connections
io.on('connection', function( socket ) {
    // Single Client's socket
    socket.emit('confirm', 'Server here');
    socket.on('from Client', function( msg ){
     console.log( msg );

server.listen( port );

client.html Source Code

<!doctype html>
   <script src='/'></script>

   var socket = io();

   socket.on( 'welcome' , function( msg ) {
       console.log( msg );

       // Contact Server
       socket.emit('from Client', 'Client Here');

   socket.on( 'msg' , function( msg ) {
       console.log( 'incoming:' , msg );