Thursday, July 13

Creating and Styling Multiple Elements in JavaScript


Description

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.appendChild(childElm);
      elm[style] = childElm;
    } else {
      switch (style){
        case "id":        elm.id = value;           break;
        case "class":
        case "className": elm.className = value;    break;
        default:          elm.style[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);



Codepen.io Example

Dynamically Style Element from Variable ( JavaScript )


Introduction

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.

Description

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){
    elm.style[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);



Codepen.io 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


Introduction

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.



Example

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


Introduction

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 = event.target;
    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);
    body.style.userSelect = 'none';
    inDrag = true;
  }
  
  function dragMove( event ) {
    if (!inDrag) return false;
    dragElement.style.left = event.clientX-dragOffsetX+'.px';
    dragElement.style.top = event.clientY-dragOffsetY+'.px';
  }
  
  function dragStop() {
    if (!inDrag) return;
    if (event.button != 0) return;
    inDrag = false;
    if ( (dragElement.offsetTop + dragElement.offsetHeight)<20) dragElement.style.top = 20 - dragElement.offsetHeight+'.px';
    if ( (dragElement.offsetLeft + dragElement.offsetWidth)<20) dragElement.style.left = 20 - dragElement.offsetWidth+'.px';
    if ( (dragElement.offsetTop+20)>window.innerHeight) dragElement.style.top = window.innerHeight - 20+'.px';
    if ( (dragElement.offsetLeft+20)>window.innerWidth) dragElement.style.left = window.innerWidth - 20+'.px';
    dragElement.zIndex = '10';
    body.style.userSelect = '';
    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


Introduction

I have noticed after watching a number of live streams on Twitch.tv 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

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


Source Code
overlay.js
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) {
      client.send(data);
    }
  });
}

wss.on('connection', function(socket){
  console.log('Client Connected!');
  socket.send('online');
  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'];
  wss.broadcast(data);
  res.send('confirmed.');
});

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

server.on( 'request', app );

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

public/index.html

package.json
{
  "name": "fs-obs-overlay",
  "version": "0.1.0",
  "description": "A Very Minimilistic Overlay System for use with OBS. Uses Express, WebSockets",
  "homepage": "http://www.failedsleep.com",
  "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


Introduction

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 twitch.tv/failedsleep. 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.


Accomplishments

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


Electron.atom.io

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


Screen shots






The Links


Tuesday, March 28

NodeJS, Socket.io: Simple Client / Server


Introduction

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



Requirements

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


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 );
 }
);

// Socket.io server listens to our app
var io = require('socket.io').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>
<html>
<head>
   <script src='/socket.io/socket.io.js'></script>
</head>
<body>

 <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 );
   });

 </script>
</body>
</html>