Nine weird things to code

So the weekend is here and you are sitting in front of your computer and don’t know what to do.
You are still bored after watching YouTube videos all day.

Don’t Worry, you have come to the right place. I will show you how to display funny text,
add a spinning 3D globe to your web page, build a calculator for your math homework or in case you work requires you to calculate the remaing fuel contents on your rocket entring an orbit around Mars. and more …

Here are 9 things you can code when you are bored.

Hello World

This “Hello World” jumps out and is a real attention seeking device. Your eyes are automatically caught paying more attention to it. If you want to drive people into madness you can display your whole page using this quirk.
You will certainly be rewarded with a firestorm of complaints.

<html>
<head><title>bored_1</title></head>
<body>

<p></p>&nbsp;<p></p>
<center><b><div id="OUT"></div></b></center>
<script>
  var div = document.getElementById ( "OUT" );
  div.innerHTML = "Hello World";
  
  function randomClr ( char )  {
    var r = parseInt ( Math.random ( ) * 255, 10 );
    var g = parseInt ( Math.random ( ) * 255, 10 );
    var b = parseInt ( Math.random ( ) * 255, 10 );
    var ret = "<font color='rgb(" + r + "," + g + "," + b + ");'>" + char + "</font>";
    return ret;
  }
  function randomType ( char )  {
    var ret=char, r = parseInt ( Math.random ( ) * 4, 10 );
    switch ( r )  {
      case 0: ret = "<b>" + char + "</b>"; break;
      case 1: ret = "<i>" + char + "</i>"; break;
      case 2: ret = "<sup>" + char + "</sup>"; break;
      case 3: ret = "<sub>" + char + "</sub>"; break;
    }
    return ret;
  }
  setInterval ( function ( ) {  
    var html="", text = "Hello World";
    for ( var t=0; t<text.length; t++ )  {
      var clr = randomClr ( text[t] );
      html += randomType ( clr );
    }
    div.innerHTML = "<h1>" + html + "</h1>";
  }, 500 );
</script>
</body>
</html>

Random Password generator

This generator will allow you to create your very own randomly generated password string.

<html>
<head><title>bored_2</title></head>
<body>
<p></p>&nbsp;<p></p>
<center><b><div id="OUT"></div></b></center>
  <script>
    var div = document.getElementById ( "OUT" );
    var randomString = function(length) {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      for(var i = 0; i < length; i++) {
          text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
      return text;
    }
    div.innerHTML = randomString ( 20 );
  </script>
</body>
</html>

I got some interesting feedback wrt this generator and decided to provide another version which will use the crypto API
inside the browsers instead of Math.random ( );

<!DOCTYPE html>
<html>
<head><title>bored_2</title></head>
<body>

<p></p>&nbsp;<p></p>
<center><b><div id="OUT"></div></b></center>
  <script>
    var div = document.getElementById ( "OUT" );
    var randomString = function(length) {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      var cryp = new  Uint8Array ( possible.length );
      var rand = getRandomValues ( cryp );

      for ( var i = 0; i < length; i++ )  {
          text += possible.charAt ( rand[i] % possible.length );
      }
      return text;
    }
    getRandomValues = function  ( buf ) {
      if (!(buf instanceof Uint8Array)) {
        throw new Error('Invalid type: buf not an Uint8Array');
      }
      if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
        window.crypto.getRandomValues(buf);
      } else if (typeof window !== 'undefined' && typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') {
        window.msCrypto.getRandomValues(buf);
      } else if (nodeCrypto) {
        var bytes = nodeCrypto.randomBytes(buf.length);
        buf.set(bytes);
      } else if (this.randomBuffer.buffer) {
        this.randomBuffer.get(buf);
      } else {
        throw new Error('No secure random number generator available.');
      }
      return buf;
    }
    div.innerHTML = randomString ( 20 );
  </script>
</body>
</html>

Santas trip

Want to move Santa across your web page to celebrate the season or have a selfie take a trip over your web page …
Here is a fun snippet to achieve that.

<!DOCTYPE html>
<html>
<head><title>bored_3</title></head>
<body bgcolor="black">
  <img src="flying.gif" id="sleigh" style="position: absolute" />
  <audio src="bells.mp3" autoplay loop></audio>
<script>
  var img = document.getElementById ( "sleigh" );
  var left = 0;
  setInterval ( function ( ) {
    left += 3;
    img.style.left = left+"px";
    if ( left > window.innerWidth )
         left = -400;
  }, 100 );
</script>
</body>
</html>

Calculator

Still don’t know what to do ?
Have you ever wondered what your monthly mortgage rate would be like if you change the interest rate or the length of the loan ?
Or are you looking for a simple tip calculator. This snippet is using evil-eval to accomplish this task.

<!DOCTYPE html>
<html>
<head><title>bored_4</title>
    <script>
      function calc ( )  {
        var out = document.getElementById ( "OUT" );
        var txt = document.getElementById ( "eq" );
        var res = eval ( txt.value );
        out.innerHTML = res+"";
      }
    </script>
</head>
<body>
  <form>
    <input type="text" id="eq" value='var r=5.00, N=12*15, P=100000; var R=r/12/100; var M=R/(1-(1+R) ** -N ) * P; P+"@"+r+"% = "+M' size="70" \>
    <input type="button" value="Calculate" onclick="calc();" \>
  </form>
<p><b><div id="OUT"> -- VALUE --</div></b>
</body>
</html>

Polar Clock

Want to know what tmie it is but you wnat to realy try to use as much brain power as possible
Try the Polar Clock. A fun way to display time.

<html>
<head>
    <title>bored_5</title>
    <script src="clock.js"> </script>
</head>
<body bgcolor="white">
<div id="logo" >
  <canvas id="canvas" width="120" height="120" ></canvas>
</div>
</body>
</html>

Random Image

Do you want to use a random background image from Flicker.
This code snippet does just that using the flickr API.

<html>
<head><title>bored_6</title>
<style>    
body {
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
}
</style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script type="text/javascript">
    var keyword = "mountains";
    function getImg ( )  {
      keyword = document.getElementById ( "key" ).value;
      var req = { tags: keyword, tagmode: "any", format: "json" };
      var url = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; 
      $.getJSON ( url, req, function ( data )  {
        var rnd = Math.floor(Math.random() * data.items.length);
        var image_src = data.items[rnd]['media']['m'].replace("_m", "_b");
        $('body').css('background-image', "url('" + image_src + "')");
      } );
    }
    $(document).ready(function(){
      getImg ( );
    });
  </script>
</head>
<body>
  <button onclick="getImg ( );">New Image</button>
  <input type="text" value="mountain" id="key"/>
</body>
</html>

Chess Game

Granted this one is a bit too much to invent yourself. But fear not, you can get the tiny 1k code for a chess game from Here …

<!doctype html>
<html>
  <!--
  (c) &copy; js1k.com, 2010 - 2017
  Note: submissions belong to their respectful owner, do not copy without their consent
  -->
  <head>
    <title>JS1k 2010 - Demo 750 </title>
    <meta charset="utf-8">
    <meta name="author" content="Óscar Toledo G.">
    <meta name="description" content="JS1k 2010 demo: Tiny Chess.">
    <meta name="pubdate" content="20100909">
    <link rel="icon" type="image/png" href="http://js1k.com/favicon.png">
    <link rel="canonical" href="http://js1k.com/2010-first/demo/750">
    <link rel="alternate" type="application/rss+xml" title="New demo feed" href="http://js1k.com/feed.xml">
    <link rel="shortlink" href="http://js1k.com/750">
    <script>
      setTimeout(function(){
        var ga = document.createElement('script');
        ga.async = true;
        ga.defer = true;
        ga.src = 'http://www.google-analytics.com/ga.js';
        ga.onload = function(){try{_gat._getTracker('UA-19882353-1')._trackPageview();}catch(e){window.console&&console.log("ga fail :'( ");};};
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga, s);
      }, 10);
    </script>
    <style>
      /* http://qfox.nl/notes/333 */
      body,html,iframe{margin:0;padding:0;border:0;width:100%;height:100%}
      iframe{position:absolute;top:0;left:0;padding-top:50px;box-sizing:border-box}
      header{position:relative;z-index:1;height:47px;padding-top:2px;border-bottom:1px solid #000;box-shadow:0 -10px 25px #ccc inset;background-color:#eee}
      aside,div,h1,p{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;text-align:center;font-size:16px;font-weight:inherit;line-height:22px;padding:0;margin:0;cursor:default}
      aside,h1{display:inline}
      a{color:#000;text-decoration:none;border-bottom:1px dashed #000}
      a:hover{border-bottom:1px solid red}
      a[href="0"]{text-decoration:line-through;pointer-events:none;border-bottom:0;color:#ccc}
      .button{float:left;width:40px;height:40px;line-height:40px;text-align:center;padding:0;margin:2px 0 0 10px;border:1px solid #888;border-color:#ddd #888 #888 #ddd;font-family:sans-serif;font-size:30px;font-weight:700;cursor:pointer}
      .button:hover{color:red;border-bottom-color:#888}
      .r{margin-right:10px}
      time{display:none}
    </style>

  </head>
  <body>
    <header>
      <div>
        <h1>
          <a href="http://js1k.com">JS1k</a>
          <a href="http://js1k.com/2010-first">2010</a>
          <strong></strong> demo
          &mdash;
           by Óscar Toledo G.
        </h1>
        <p>
          <em>
            Tiny Chess.
          </em>
        </p>
        <aside>
          &mdash;
          1023 bytes
          &mdash;
          <!-- -->
          <a href="http://js1k.com/2010-first/details/750">demo details</a>
          &mdash;
          <a href="http://js1k.com/2010-first/demos">list of demos</a>
          <!-- 
          <b><a href="http://js1k.com/2010-first/demo/">
            Update available here!
          </a></b>
          <!-- -->
          &mdash;
          <a href="http://js1k.com/750" title="short link for your mobile devices" rel="nofollow">js1k.com/750</a>
        </aside>
      </div>

      <a href="749" class="button p">&Larr;</a>
      <a href="751" class="button n">&Rarr;</a>
    </header>

    <script type="demo">
for(B=i=y=u=b=i=5-5,x=10,I=[],l=[];B++<304;I[B-1]=B%x?B/x%x<2|B%x<2?7:B/x&4?0:l[i++]="ECDFBDCEAAAAAAAAIIIIIIIIMKLNJLKM@G@TSb~?A6J57IKJT576,+-48HLSUmgukgg OJNMLK  IDHGFE".charCodeAt(y++)-64:7);function X(c,h,e,s){c^=8;for(var o,S,C,A,R,T,G,d=e&&X(c,0)>1e4,n,N=-1e8,O=20,K=78-h<<9;++O<99;)if((o=I[T=O])&&(G=o^c)<7){A=G--&2?8:4;C=o-9?l[61+G]:49;do if(!(R=I[T+=l[C]])&&!!G|A<3||(R+1^c)>9&&G|A>2){if(!(R-2&7))return K;n=G|(c?T>29:T<91)?o:6^c;S=(R&&l[R&7|32]*2-h-G)+(n-o?110:!G&&(A<2)+1);if(e>h||1<e&e==h&&S>2|d){I[T]=n;I[O]=0;S-=X(c,h+1,e,S-N);if(!(h||e-1|B-O|T-b|S<-1e4))return W(),c&&setTimeout("X(8,0,2),X(8,0,1)",75);I[O]=o;I[T]=R}if(S>N||!h&S==N&&Math.random()<.5)if(N=S,e>1)if(h?s-S<0:(B=O,b=T,0))break}while(!R&G>2||(T=O,(G||A>2|(c?O>78:O<41)&!R)&&++C*--A))}return-K+768<N|d&&N}function W(){i="<table>";for(u=18;u<99;document.body.innerHTML=i+=++u%x-9?"<th width=60 height=60 onclick='I[b="+u+"]>8?W():X(0,0,1)'style='font-size:50px'bgcolor=#"+(u-B?u*.9&1||9:"d")+"0f0e0>&#"+(I[u]?9808+l[67+I[u]]:160):u++&&"<tr>")B=b}W()
    </script>
    <script>
      (function(){var doc=document;var header=doc.getElementsByTagName("header")[0];var firstChild=header.firstChild;var p=doc.getElementsByClassName("p")[0];var n=doc.getElementsByClassName("n")[0];header.insertBefore(p,firstChild);header.insertBefore(n,firstChild);header.appendChild(doc.getElementsByTagName("p")[0])})();
      (function reload(){var doc=document;var header=doc.getElementsByTagName("header")[0];var iframe=doc.createElement("iframe");doc.body.appendChild(iframe);var iwin=iframe.contentWindow;var idoc=iframe.contentDocument;idoc.open();idoc.close();idoc.write('<!doctype html><head><meta charset="utf-8"><body>');idoc.head.innerHTML="<style>\n"+"html, body { margin: 0; padding: 0; border: 0; width: 100%; height: 100%; }\n"+"</style>\n";idoc.body.innerHTML="\n\t\t"+"<canvas"+' id="c"'+''+"></canvas>\n"+
      (false?"<script>\x3c/script>\n":"")+"";var Audio=iwin.Audio;iwin.Audio=function(x){return new Audio(x)};if(false){var canvas=idoc.getElementsByTagName("canvas")[0];iwin.a=canvas.getContext("2d");iwin.b=idoc.body;iwin.c=canvas;var p2d=iwin.Path2D;function wrap(ctx){var fill=ctx.fill,clip=ctx.clip,stroke=ctx.stroke;ctx.scale=ctx.scale;ctx.drawFocusIfNeeded=ctx.drawFocusIfNeeded;ctx.ellipse=ctx.ellipse;ctx.fill=function(r){fill.call(ctx,r==="evenodd"?"evenodd":"nonzero")};ctx.stroke=
        function(p){if(p&&p2d&&p instanceof p2d)stroke.call(ctx,p);else stroke.call(ctx)};ctx.clip=function(p){if(p&&p2d&&p instanceof p2d)clip.call(ctx,p);else clip.call(ctx)};return ctx}if(false){var cvs=iwin.c;var cNode=cvs.cloneNode;cvs.cloneNode=function(){var clone=cNode.apply(cvs,arguments);var cloneGet=clone.getContext;clone.getContext=function(){return wrap(cloneGet.call(clone,"2d"))};return clone};var get=cvs.getContext;cvs.getContext=function(){return wrap(get.call(cvs,"2d"))}}if(false)wrap(iwin.a)}idoc.body.clientWidth;
        var demo=idoc.createElement("script");var scrpt=doc.querySelector('script[type="demo"]').textContent.replace(/m.location=m.location;/,"top.reload();");if(false)scrpt="A=0,B=0;"+scrpt;demo.textContent=scrpt;idoc.body.appendChild(demo);idoc.close();iframe.contentWindow.focus();var r=doc.createElement("div");r.innerHTML="&#8635;";r.className="button r";r.title="restart just the demo (local, without remote fetch)";window.reload=r.onclick=function(){doc.body.removeChild(iframe);r.parentElement.removeChild(r);
          iframe=null;r=null;idoc=null;header=null;reload()};var firstLine=doc.getElementsByTagName("div")[0];header.insertBefore(r,firstLine)})();
    </script>
  </body>
</html>

3D Globe

And finally here is a quick way to add a 3D globe to your web page using OpenGlobus.

<html>
<head><title>OpenGlobus - Earth planet</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.rawgit.com/OpenGlobus/OpenGlobus/eb8392c2/build/og.css" type="text/css" />
    <script src="https://cdn.rawgit.com/OpenGlobus/OpenGlobus/eb8392c2/build/og.js"></script>
</head>
<body>
    <div id="globus" style="width:100%;height:80%"></div>
    <button id="btnOSM">OSM</button>
    <button id="btnMQS">MapQuest Sat.</button>
    <script>

        document.getElementById("btnOSM").onclick = function () {
            osm.setVisibility(true);
        };

        document.getElementById("btnMQS").onclick = function () {
            sat.setVisibility(true);
        };

        var osm = new og.layer.XYZ("OpenStreetMap", {
            specular: [0.0003, 0.00012, 0.00001],
            shininess: 20,
            diffuse: [0.89, 0.9, 0.83],
            isBaseLayer: true,
            url: "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
            visibility: true,
            attribution: 'Data @ OpenStreetMap contributors, ODbL'
        });

        var sat = new og.layer.XYZ("MapQuest Satellite", {
            shininess: 20,
            specular: og.math.vector3(0.00048, 0.00037, 0.00035),
            diffuse: og.math.vector3(0.88, 0.85, 0.8),
            ambient: og.math.vector3(0.15, 0.1, 0.23),
            isBaseLayer: true,
            url: "https://api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoibWdldmxpY2giLCJhIjoiY2o0ZmVudncwMGZvbjJ3bGE0OGpsejBlZyJ9.RSRJLS0J_U9_lw1Ti1CmsQ",
            visibility: false,
            attribution: '@2014 MapQuest - Portions @2014 "Map data @ <a target="_blank" href="http://www.openstreetmap.org/">OpenStreetMap</a> and contributors, <a target="_blank" href="http://opendatacommons.org/licenses/odbl/"> CC-BY-SA</a>"'
        });

        var controls = [
            og.control.mouseNavigation(),
            og.control.touchNavigation(),
            og.control.zoomControl(),
            og.control.earthCoordinates(),
            og.control.sun()
        ];

        globus = new og.Globus({
            "target": "globus",
            "name": "Earth",
            "controls": controls,
            "terrain": new og.terrainProvider.TerrainProvider("OpenGlobus"),
            "layers": [osm, sat]
        });
    </script>
</body>
</html>

Resources

So now that you know what to do it should be easy to take some of these suggestions and run with it. If nothing else you can find plenty more on gihub.com to help you kill off some of your time.

You can directly follow the link to the Battlefield to play with the code.

I also created a video for these drive-by-coding samples, which you can find here …

One thought on “Nine weird things to code”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.