Visualizzazione post con etichetta HTML5 JS CSS3. Mostra tutti i post
Visualizzazione post con etichetta HTML5 JS CSS3. Mostra tutti i post

martedì 19 maggio 2015

Tutorial: Canvas in HTML5




Let's play a bit with the graphic & Canvas...
You can find the code here:
http://jsbin.com/umaDEvu/5/edit?html,output

 <!DOCTYPE HTML>  
 <html>  
   <head>  
     <style>  
       body {  
         margin: 0px;  
         padding: 0px;  
       }  
       #myCanvas {  
         border: 1px solid #9C9898;  
       }  
     </style>  
     <script>     
       var clicked = 0;  
       var loopMouth = 0;  
       var lastMouseX = 300;  
       var lastMouseY = 300;  
       var colorSetIndex = 2;  
       var colorSet = [["limegreen", "forestgreen", "darkgreen", "olive"],   
               ["mediumblue", "blue", "darkblue", "indigo"],   
               ["darkorange", "peru", "sienna", "darkgoldenrod"]];  
      function setColorSetIndex(colorIndex){  
       colorSetIndex = colorIndex;  
      }  
       function getMousePos(canvas, evt) {  
         // get canvas position  
         var obj = canvas;  
         var top = 0;  
         var left = 0;  
         while (obj && obj.tagName != 'BODY') {  
           top += obj.offsetTop;  
           left += obj.offsetLeft;  
           obj = obj.offsetParent;  
         }  
         lastMouseX = evt.clientX - left + window.pageXOffset;  
         lastMouseY = evt.clientY - top + window.pageYOffset;  
       }  
      function drawFace(context) {  
         //left ear  
         context.beginPath();  
         var grd = context.createRadialGradient(125, 130, 10, 175, 130, 100);  
         grd.addColorStop(0.01, colorSet[colorSetIndex][0]);  
         grd.addColorStop(0.5, colorSet[colorSetIndex][1]);  
         grd.addColorStop(0.7, colorSet[colorSetIndex][2]);  
         grd.addColorStop(0.95, colorSet[colorSetIndex][3]);  
         context.arc(175, 150, 75, 0, 2*Math.PI, false);  
         context.fillStyle = grd;  
         context.fill();  
         // right ear  
         context.beginPath();  
         var grd = context.createRadialGradient(450, 95, 10, 425, 130, 100);  
         grd.addColorStop(0.01, colorSet[colorSetIndex][0]);  
         grd.addColorStop(0.5, colorSet[colorSetIndex][1]);  
         grd.addColorStop(0.7, colorSet[colorSetIndex][2]);  
         grd.addColorStop(0.95, colorSet[colorSetIndex][3]);  
         context.arc(425, 125, 75, 0, 2*Math.PI, false);  
         context.fillStyle = grd;  
         context.fill();  
         //face  
         context.beginPath();  
         var grd = context.createRadialGradient(300, 140, 50, 300, 170, 175);  
         grd.addColorStop(0.01, colorSet[colorSetIndex][0]);  
         grd.addColorStop(0.5, colorSet[colorSetIndex][1]);  
         grd.addColorStop(0.7, colorSet[colorSetIndex][2]);  
         grd.addColorStop(0.95, colorSet[colorSetIndex][3]);  
         context.arc(300, 200, 150, 0, 2*Math.PI, false);  
         context.fillStyle = grd;  
         context.fill();  
      }  
      function drawEyes(context, mx, my) {  
         var cx = [300, 220, 200, 250, 380, 350, 400];  
         var cy = [100, 130, 170, 160, 130, 150, 185];  
         var ray = [ 30, 20, 10, 10, 20, 10, 10];  
         for (var i = 0; i < cx.length; i++) {  
          //compute the multiplier for the mouse position  
          var mmx = ((mx-300)/300*ray[i]);  
          var mmy = ((my-200)/200*ray[i]);  
          context.beginPath();  
          var grd = context.createRadialGradient(cx[i]+mmx, cy[i]+mmy, 1, cx[i]+mmx, cy[i]+mmy, ray[i]*3);  
          grd.addColorStop(0.01, "black");  
          grd.addColorStop(0.1, "white");  
          grd.addColorStop(0.99, "gray");  
          context.arc(cx[i], cy[i], ray[i], 0, 2*Math.PI, false);  
          context.fillStyle = grd;  
          context.fill();    
         }  
      }  
      function drawMouth(context) {  
         var grd_m = context.createRadialGradient(300, 300, 10, 300, 300, 100);  
         grd_m.addColorStop(0.1, "red");  
         grd_m.addColorStop(0.6, "black");  
       //for closing the mouth  
       var diffLeft;  
       var diffRight;   
       //loopMouth goes from 0-100  
       // from 0-50 it close the mouth  
       //from 50-100 it reopen the mouth  
       if(loopMouth < 50)  
       {  
        tempLoopMouth = loopMouth;  
        diffLeft=((380-230)/50)*(tempLoopMouth+1);  
        diffRight=((330-250)/50)*(tempLoopMouth+1);  
       }  
       else   
       {  
        tempLoopMouth = (100-loopMouth);  
        diffLeft=((380-230)/50)*(tempLoopMouth+1);  
        diffRight=((330-250)/50)*(tempLoopMouth+1);  
       }   
         context.beginPath();  
         context.moveTo(220, 230);  
         context.bezierCurveTo(220, 380 - diffLeft, 380, 330 - diffRight, 380, 250);  
         context.closePath(); // complete custom shape  
         context.fillStyle = grd_m;  
         context.fill();  
      }       
      function drawBackground(context){  
         //set the background  
         var grd = context.createRadialGradient(300, 200, 50, 300, 200, 600);  
         grd.addColorStop(0.01, "white");  
         grd.addColorStop(0.5, "black");  
         context.arc(300, 200, 600, 0, 2*Math.PI, false);  
         context.fillStyle = grd;  
         context.fill();  
      }  
      function drawAll(context){  
           drawBackground(context);  
           drawFace(context);  
           drawEyes(context, lastMouseX, lastMouseY);  
           drawMouth(context);  
      }        
      // requestAnim shim layer by Paul Irish    
      window.requestAnimFrame = (function(){    
      return window.requestAnimationFrame ||    
       window.webkitRequestAnimationFrame ||    
       window.mozRequestAnimationFrame ||    
       window.oRequestAnimationFrame ||    
       window.msRequestAnimationFrame ||    
       function(/* function */ callback, /* DOMElement */ element){    
       window.setTimeout(callback, 1000 / 60);    
       };    
      })();     
      function animationLoop(){  
       var canvas = document.getElementById("myCanvas");  
       var context = canvas.getContext("2d");  
       if(clicked == 1)  
         loopMouth++;  
       if(loopMouth==100)  
       {  
         loopMouth = 0;  
         clicked = 0;  
       }  
       drawAll(context);  
       requestAnimFrame(animationLoop);        
      }  
       window.onload = function(){  
         var canvas = document.getElementById("myCanvas");  
         var context = canvas.getContext("2d");  
         canvas.addEventListener('mousemove', function (evt) {  
           var mousePos = getMousePos(canvas, evt);  
           drawAll(context);  
         }, false);  
         canvas.addEventListener('click', function (evt) {  
           var mousePos = getMousePos(canvas, evt);  
           if(clicked == 0)   
            clicked = 1;   
         }, false);  
         drawAll(context, 300, 200);  
         // Start animation  
         animationLoop();  
       };  
     </script>  
   </head>  
   <body onmousedown="return false;">  
     <canvas id="myCanvas" width="600" height="400">  
     </canvas>  
    <button onclick="setColorSetIndex(0)"> green </button>  
    <button onclick="setColorSetIndex(1)"> blue </button>  
    <button onclick="setColorSetIndex(2)"> orange </button>  
    <div id="help">  
     Animations are:   
     <ul>  
      <li> moving mouse on the canvas = move eyes; </li>  
      <li> click on the canvas = close mouth; </li>  
      <li> click on the buttons = change monster color; </li>  
     </ul>  
    </div>  
     </body>  
 </html>  


As you can see, there is basically no HTML. It is a pure drawing made in Javascript...

sabato 1 novembre 2014

Sankey Diagram with D3JS




I received a task recently which gave me a lot of fun.
I had to create a diagram like the one above with adapted numbers for my company core business.
The idea was to have such numbers in a Power point. One of the biggest challenge was to dig in the DB in order to find the correct informations (but this is beyond the scope of this post).
One of the funniest task was to build the power point presentation! How can I build a power point reporting the information such the one in the diagram above?

I googled it and I discovered that this diagram is called "Sankey" diagram.
I tried then to find any tool who was supporting the creation of those type of diagrams.
Of course, first choice was google chart:
https://developers.google.com/chart/interactive/docs/gallery/sankey

I found that this lybrary is quite static, it does not give too much freedom. Additionally the graphic is quite poor.

I searched deeper and I fell in love for the library D3js
http://d3js.org/

This library support too many of the non conventional diagrams. No words to mention, just have a look at the examples:
https://github.com/mbostock/d3/wiki/Gallery

I must confess that it is not really straightforward, not as easy as the google chart one.
As well the possibilities are enormous.

In this post I want to have my usual copy and paste snippets.
I found a very interesting tutorial here:
http://bl.ocks.org/d3noob/5028304

I have reported here the result of my task (of course number changed):
http://marcoandolfi.eu5.org/sankey_test/viewer.html

And now the copy and paste part.
You need three things:
- The javascript library
- The json file.
- The HTML file rendering it.

The javascript library Sankey.js, I stored a copy on my website here).
Here it follow an example of possible JSON file. Very easy: links and nodes.

 {  
 "links": [  
 {"source":"1A","target":"2A","value":"10"},  
 {"source":"1A","target":"2B","value":"1" },  
 {"source":"1B","target":"2B","value":"15"},  
 {"source":"1C","target":"2A","value":"20"},  
 {"source":"1C","target":"2B","value":"14"},  
 {"source":"1C","target":"2C","value":"45"},  
 {"source":"1D","target":"2A","value":"25"},  
 {"source":"1D","target":"2C","value":"25"},  
 {"source":"2A","target":"3A","value":"9" },  
 {"source":"2A","target":"3B","value":"15"},  
 {"source":"2A","target":"3C","value":"28"},  
 {"source":"2A","target":"3D","value":"17"},  
 {"source":"2B","target":"3B","value":"15"},  
 {"source":"2B","target":"3C","value":"15"},  
 {"source":"2C","target":"4B","value":"50"},  
 {"source":"3A","target":"4A","value":"10"},  
 {"source":"3B","target":"4B","value":"20"},  
 {"source":"3B","target":"4A","value":"5" },  
 {"source":"3C","target":"4B","value":"40"}  
 ] ,  
 "nodes": [  
 {"name":"1A"},  
 {"name":"1B"},  
 {"name":"1C"},  
 {"name":"1D"},  
 {"name":"2A"},  
 {"name":"2B"},  
 {"name":"2C"},  
 {"name":"3A"},  
 {"name":"3B"},  
 {"name":"3C"},  
 {"name":"3D"},  
 {"name":"4A"},  
 {"name":"4B"}  
 ] }  


Finally the HTML page (it is needed to adapt only the bold part: Json file name or ajax call and the location of your Sankey.js).
 <!DOCTYPE html>  
 <meta charset="utf-8">  
 <title>SANKEY Experiment</title>  
 <style>  
 .node rect {  
  cursor: move;  
  fill-opacity: .9;  
  shape-rendering: crispEdges;  
 }  
 .node text {  
  pointer-events: none;  
  text-shadow: 0 1px 0 #fff;  
 }  
 .link {  
  fill: none;  
  stroke: #000;  
  stroke-opacity: .2;  
 }  
 .link:hover {  
  stroke-opacity: .5;  
 }  
 </style>  
 <body>  
 <p id="chart">  
 <script src="http://d3js.org/d3.v3.js"></script>  
 <script src="sankey.js"></script>  
 <script>  
 var units = "Widgets";  
 var margin = {top: 10, right: 10, bottom: 10, left: 10},  
   width = 1200 - margin.left - margin.right,  
   height = 740 - margin.top - margin.bottom;  
 var formatNumber = d3.format(",.0f"),  // zero decimal places  
   format = function(d) { return formatNumber(d) + " " + units; },  
   color = d3.scale.category20();  
 // append the svg canvas to the page  
 var svg = d3.select("#chart").append("svg")  
   .attr("width", width + margin.left + margin.right)  
   .attr("height", height + margin.top + margin.bottom)  
  .append("g")  
   .attr("transform",   
      "translate(" + margin.left + "," + margin.top + ")");  
 // Set the sankey diagram properties  
 var sankey = d3.sankey()  
   .nodeWidth(36)  
   .nodePadding(10)  
   .size([width, height]);  
 var path = sankey.link();  
 // load the data  
 d3.json("data.json", function(error, graph) {  
   var nodeMap = {};  
   graph.nodes.forEach(function(x) { nodeMap[x.name] = x; });  
   graph.links = graph.links.map(function(x) {  
    return {  
     source: nodeMap[x.source],  
     target: nodeMap[x.target],  
     value: x.value  
    };  
   });  
  sankey  
    .nodes(graph.nodes)  
    .links(graph.links)  
    .layout(32);  
 // add in the links  
  var link = svg.append("g").selectAll(".link")  
    .data(graph.links)  
   .enter().append("path")  
    .attr("class", "link")  
    .attr("d", path)  
    .style("stroke-width", function(d) { return Math.max(1, d.dy); })  
    .sort(function(a, b) { return b.dy - a.dy; });  
 // add the link titles  
  link.append("title")  
     .text(function(d) {  
         return d.source.name + " → " +   
         d.target.name + "\n" + format(d.value); });  
 // add in the nodes  
  var node = svg.append("g").selectAll(".node")  
    .data(graph.nodes)  
   .enter().append("g")  
    .attr("class", "node")  
    .attr("transform", function(d) {   
            return "translate(" + d.x + "," + d.y + ")"; })  
   .call(d3.behavior.drag()  
    .origin(function(d) { return d; })  
    .on("dragstart", function() {   
            this.parentNode.appendChild(this); })  
    .on("drag", dragmove));  
 // add the rectangles for the nodes  
  node.append("rect")  
    .attr("height", function(d) { return d.dy; })  
    .attr("width", sankey.nodeWidth())  
    .style("fill", function(d) {   
            return d.color = color(d.name.replace(/ .*/, "")); })  
    .style("stroke", function(d) {   
            return d3.rgb(d.color).darker(2); })  
   .append("title")  
    .text(function(d) {   
            return d.name + "\n" + format(d.value); });  
 // add in the title for the nodes  
  node.append("text")  
    .attr("x", -6)  
    .attr("y", function(d) { return d.dy / 2; })  
    .attr("dy", ".35em")  
    .attr("text-anchor", "end")  
    .attr("transform", null)  
    .text(function(d) { return d.name; })  
   .filter(function(d) { return d.x < width / 2; })  
    .attr("x", 6 + sankey.nodeWidth())  
    .attr("text-anchor", "start");  
 // the function for moving the nodes  
  function dragmove(d) {  
   d3.select(this).attr("transform",   
     "translate(" + (  
            d.x = Math.max(0, Math.min(width - d.dx, d3.event.x))  
          ) + "," + (  
           d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))  
       ) + ")");  
   sankey.relayout();  
   link.attr("d", path);  
  }  
 });  
 </script>  
 </body>  
 </html>  


Most probably you want to run the first test on your machine. Therefore you need to launch your browser in a "special mode" so that it will be able to read local file (for securityy reason browser deactivate this mode). I like Chrome and therefore what follows is valid only for Chrome, but extremely similar is for the other browser.

First be sure that you have killed every process of Chrome, which does not simply mean to close the browser, but to open the task manager and kill every process.
Then create a batch file like this (or invoke from command line):

 cd "C:\Program Files (x86)\Google\Chrome\Application"  
 chrome.exe --allow-file-access-from-files  



lunedì 3 marzo 2014

Responsive HTML5 menu

I need a menu that is adaptative, so much that if I open it from a laptop that it is already exploded but if I open it from a mobile device, then it needs to be clicked and exploded.

Such tool I used on my web site. If I see my resume section:
http://marcoandolfi.eu5.org/cv.html

you have this view from your laptop:

Instead if you open it from your iPhone you should have a view like this:

First view:



When Opened:



Ok, nice! How? 

First of all you need a JS which is the main engine 
(on my website is a separate file "dropdown-menu.js"): 
   
 if(window.addEventListener){   
      window.addEventListener("load", doLoad, false);  
 }else if(window.attachEvent){   
      window.attachEvent("onload", doLoad);  
 }else if(window.onLoad){  
   window.onload = doLoad;  
 }  
   
function doLoad(){  
        var nav = document.getElementsByTagName("NAV")[0];  
        var childs = nav.childNodes;  
        for(var i = 0; i < childs.length; i++){  
        var child = childs[i];  
        if(child.tagName === "H2"){  
          child.onclick = function(){toogleMenu(nav)};  
          child.onfocus = function(){toogleMenu(nav)};  
          break;  
        }  
}  
   
      var elClass = nav.className;  
      var arrClasses = elClass.split(" ");  
      for(var i = 0; i < arrClasses.length; i++){  
         if(arrClasses[i] === "expanded") arrClasses.splice(i, 1);  
      }  
      nav.className = arrClasses.join(" ");  
      nav.className += " non-expanded";  
      return false;  
 };  
   
 function toogleMenu(el){  
      var elClass = el.className;  
      var arrClasses = elClass.split(" ");  
      for(var i = 0; i < arrClasses.length; i++){  
        if(arrClasses[i] === "expanded"){  
          arrClasses.splice(i, 1);  
          arrClasses[length + 1] = "non-expanded";  
        }  else if(arrClasses[i] === "non-expanded"){  
          arrClasses.splice(i, 1);  
          arrClasses[length + 1] = "expanded";  
        }  
      }  
      el.className = arrClasses.join(" ");  
      return false;  
 }  




Then a bit of CSS 
   
 nav h2, aside h2{  
      position: absolute;  
      left: -999em;  
 }  
   
 nav {  
      clear: left;  
      margin: 0 0 2em;  
 }  
   
 nav ol{  
      border: 1px solid #e6e6e6;  
      padding-left: 0;  
 }  
   
 nav li {  
      border-bottom: 1px solid #eee;  
      line-height: 2em;  
      list-style: none;  
      margin-left: 0;  
 }  
   
 nav li:last-child {  
   border-bottom: 0;  
 }  
   
 nav a {  
      color: #999;  
      display: block;  
      padding: .5em .8em;  
      text-decoration: none;  
 }  
   
 nav .current {  
      font-weight: bold;  
 }  
   
 .dropdown-header {  
      font-size: 14px;  
      font-weight: bold;  
      color: #000000;  
 }  
   
 @media screen and (max-width: 37.499em){ /* base: 16px -> [< 600px] */  
   
      nav {  
           margin: 0 0 1.5em;  
           overflow: hidden;  
           position: relative;  
      }  
   
      nav h2 {  
           cursor: pointer;  
           font-size: 0.5em;  
           height: 4.2em;   
           left: auto;  
           margin: 0;  
           right: 0;  
           position: absolute;  
           text-indent: -999em;  
           top: 0;  
           width: 4em;  
      }  
   
      nav.non-expanded h2 {  
           background: #ccc url(../img/check_icon.png) no-repeat -35px 45%;  
      }  
   
      nav.expanded h2 {  
           background: #ccc url(../img/check_icon.png) no-repeat 0px 45%;  
      }  
   
      nav h2{  
           background: none;  
      }  
   
      nav a {  
           padding-right: 3em;  
      }  
   
      nav li {  
           clear: left;  
           line-height: 1em;  
      }  
   
      nav.non-expanded li{  
           display: none;  
      }  
   
      nav.expanded li{  
           display: block;  
      }  
   
      nav li.current {  
           border-bottom-width: 0;  
           display: block;  
      }  
   
      nav.expanded li.current {  
           border-bottom-width: 1px;  
      }  
   
 }  
(on my website is a separate file "dropdown-menu.css"): 





and now the HTML:

 <!DOCTYPE html>  
 <html lang="en">  
  <head>  
   [...]  
   <!-- Bootstrap core CSS -->  
   <link href="css/bootstrap.min.css" rel="stylesheet">  
   <!-- CSS for drop down menú adaptive -->  
   <link href="css/dropdown-menu.css" rel="stylesheet">  
   [...]  
  </head>  
  <body>  
    [...]          
       <nav>  
        <h2>Documents</h2>  
         <ol>  
           <li class="dropdown-header"> Professional </li>  
           <li class="selectable" id="CV"><a href="javascript:loadFrame('CV');">Curriculum Vitae</a></li>  
           <li class="selectable" id="ProjectList"><a href="javascript:loadFrame('ProjectList');">Project List</a></li>  
           <li class="selectable" id="Recommendation"><a href="javascript:loadFrame('Recommendation');">Recommendation</a></li>  
           <li class="dropdown-header"> Education </li>  
           <li class="selectable" id="HighSchoolDiploma"><a href="javascript:loadFrame('HighSchoolDiploma');">High School Diploma</a></li>  
           <li class="selectable" id="Bachelor"><a href="javascript:loadFrame('Bachelor');">Bachelor Degree</a></li>  
           <li class="selectable" id="Master"><a href="javascript:loadFrame('Master');">Master Degree</a></li>  
           <li class="selectable" id="Paper"><a href="javascript:loadFrame('Paper');">Scientific publication</a></li>  
           <li class="dropdown-header"> Certification </li>  
           <li class="selectable" id="TUV"><a href="javascript:loadFrame('TUV');">PM Certification</a></li>  
           <li class="selectable" id="Scrum"><a href="javascript:loadFrame('Scrum');">Scrum Master Certification</a></li>  
           <li class="selectable" id="HTML5"><a href="javascript:loadFrame('HTML5');">HTML5 Certification</a></li>  
           <li class="selectable" id="SAPHANA"><a href="javascript:loadFrame('SAPHANA');">SAP HANA Certification</a></li>  
         </ol>  
       </nav>  
   [...]  
   <!-- Bootstrap core JavaScript  
   ================================================== -->  
   <!-- Placed at the end of the document so the pages load faster -->  
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>  
   <script src="js/dropdown-menu.js"></script>  
   <script src="js/bootstrap.min.js"></script>  
   [...]  
  </body>  
 </html>  

eh voilá!


Constraint: 
The JS is based on the search of the tag <nav>.
This means: if you have more than one <nav> tag potentially it will not work. You need to have only one <nav>. It is easy to extend to code and change the search of the tag not on the tag type, but on the tag id.

venerdì 28 febbraio 2014

CSS Checklist effect

You want to achieve in HTML such effect using only CSS. 




Thanks to www.cssflow.com ! They made a great tutorial. 
Basically you can find everything needed here: http://www.cssflow.com/snippets/simple-to-do-list



mercoledì 26 febbraio 2014

Responsive picture resizer

You are building your website and you have a pretty heavy picture. You would like to have a picture which is small for small device and large for normal laptop.
I just did on my website, for my main picture:

(1014 x 490) to be used on laptop


(792 x 400) to be used on tablets


(300 x 253) to be used on mobile devices



How do you do that?
There is a great a very lightweight script fully supporting you (thanks to Koen Vendrik, please visit his website: http://kvendrik.com)


 /*  
 // @name: Responsive-img.js  
 // @version: 1.1  
 //   
 // Copyright 2013-2014 Koen Vendrik, http://kvendrik.com  
 // Licensed under the MIT license  
 */  
 function makeImagesResponsive() {  
   var e = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,  
     t = document.getElementsByTagName("body")[0].getElementsByTagName("img");  
   if (t.length === 0) return;  
   var n;  
   t[0].hasAttribute ? n = function (e, t) {  
     return e.hasAttribute(t)  
   } : n = function (e, t) {  
     return e.getAttribute(t) !== null  
   };  
   var r = window.devicePixelRatio ? window.devicePixelRatio >= 1.2 ? 1 : 0 : 0;  
   for (var i = 0; i < t.length; i++) {  
     var s = t[i],  
       o = r && n(s, "data-src2x") ? "data-src2x" : "data-src",  
       u = r && n(s, "data-src-base2x") ? "data-src-base2x" : "data-src-base";  
     if (!n(s, o)) continue;  
     var a = n(s, u) ? s.getAttribute(u) : "",  
       f = s.getAttribute(o),  
       l = f.split(",");  
     for (var c = 0; c < l.length; c++) {  
       var h = l[c].replace(":", "||").split("||"),  
         p = h[0],  
         d = h[1],  
         v, m;  
       if (p.indexOf("<") !== -1) {  
         v = p.split("<");  
         if (l[c - 1]) {  
           var g = l[c - 1].split(/:(.+)/),  
             y = g[0].split("<");  
           m = e <= v[1] && e > y[1]  
         } else m = e <= v[1]  
       } else {  
         v = p.split(">");  
         if (l[c + 1]) {  
           var b = l[c + 1].split(/:(.+)/),  
             w = b[0].split(">");  
           m = e >= v[1] && e < w[1]  
         } else m = e >= v[1]  
       } if (m) {  
         var E = d.indexOf("//") !== -1 ? 1 : 0,  
           S;  
         E === 1 ? S = d : S = a + d;  
         s.src !== S && s.setAttribute("src", S);  
         break  
       }  
     }  
   }  
 }  
 if (window.addEventListener) {  
   window.addEventListener("load", makeImagesResponsive, !1);  
   window.addEventListener("resize", makeImagesResponsive, !1)  
 } else {  
   window.attachEvent("onload", makeImagesResponsive);  
   window.attachEvent("onresize", makeImagesResponsive)  
 };  


Here comes the HTML code:


 <!DOCTYPE html>  
 <html lang="en">  
  <head>  
   [...]   
  </head>  
  <body>  
   [...]  
     <figure>  
      <img width="100%"  
       src="img/Marco_andolfi_1024.png"   
       alt="Marco Andolfi"   
       data-src-base='img/'   
       data-src='<600:Marco_Andolfi_600.png,   
            <800:Marco_Andolfi_800.png,   
            >800:Marco_Andolfi_1024.png'>  
     </figure>   
   [...]   
   <script src="js/responsive-img.js"></script>  
  </body>  
 </html>  





venerdì 21 febbraio 2014

Motion scroll effect




Ok, it is one line of code, but I continuously forget it.
You place an anchor on your web site, but you do not like the immediate jump. You would prefer a motion that bring you to the anchor and let you understand that you are moving.

Well the code is extremely easy and you need just to import a jQuery library.
 
/*******  
      ***     Anchor Slider by Cedric Dugas  ***  
      *** Http://www.position-absolute.com ***  
      Never have an anchor jumping your content, slide it.  
      Don't forget to put an id to your anchor !  
      You can use and modify this script for any project you want, but please leave this comment as credit.  
      File: jquery.anchor.js
*****/  
 $(document).ready(function() {  
      $("a.anchorLink").anchorAnimate()  
 });  
 jQuery.fn.anchorAnimate = function(settings) {  
       settings = jQuery.extend({  
           speed : 1100  
      }, settings);       
      return this.each(function(){  
           var caller = this  
           $(caller).click(function (event) {       
                event.preventDefault()  
                var locationHref = window.location.href  
                var elementClick = $(caller).attr("href")  
                var destination = $(elementClick).offset().top;  
                $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {  
                     window.location.hash = elementClick  
                });  
                 return false;  
           })  
      })  
 }  


And here is the HTML:


 <!doctype html>  
 <head>  
   [...]  
 </head>  
 <body>  
   [...]  
   </header>  
   [...]  
    <div>  
      <div>  
       <h2>Menu</h2>  
       <ul>  
        <li><a href="#anchor_master" class="anchorLink">Master degree</a></li>  
        <li><a href="#anchor_bachelor" class="anchorLink">Bachelor degree</a></li>  
        <li><a href="#anchor_projects" class="anchorLink">University projects</a></li>  
        <li><a href="#anchor_highschool" class="anchorLink">High School</a></li>  
       </ul>  
      </div>  
        [...]  
       <div  id="master_degree">  
       <span id="anchor_master"></span>  
        [...]  
       </div>  
       <div id="bachelor_degree">  
        <span id="anchor_bachelor"></span>  
        [...]  
       </div>  
       <div id="projects">  
        <span id="anchor_projects"></span>  
        [...]  
       </div>  
       <div id="highschool">  
        <span id="anchor_highschool"></span>  
        [...]  
       </div>  
      </div>  
  </div>  
   [...]  
   <script>window.jQuery || document.write("<script src='scripts/jquery-1.8.2.min.js'>\x3C/script>")</script>  
   <script type="text/javascript" src="scripts/jquery.anchor.js"></script>  
 </body>  
 </html>  

Notice: i
It is needed only the import of the JS file and that the link has the class="anchorLink"
For the rest is a normal HTML, you do not need any special id, class, etc...

martedì 11 febbraio 2014

Chart JS

You need to have a easy a quick chart for your website. 
Here there is a free JS library, fast, light and easy to use. 


It can cover the most common needs, it is free and it is very easy to use and also well documented.
It is missing just the legend: there is no legend you can add...
But actually I found on internet a fix for it.
In particular there is:



I used it for my website as well. Here a short tutorial.
In order to explain my language skills, I have used a bit of iconographic and this is the result 




I choose the following chart and then I have included the correspondent legend.


You need first of all Chart.js, you can find it here: 

Then you need to add the JS file for the legend. You can find it here: 



I think that the code of the legend is amazing because (currently) it is just that: 
 function legend(parent, data) {  
   parent.className = 'legend';  
   var datas = data.hasOwnProperty('datasets') ? data.datasets : data;  
   datas.forEach(function(d) {  
     var title = document.createElement('span');  
     title.className = 'title';  
     title.style.borderColor = d.hasOwnProperty('strokeColor') ? d.strokeColor : d.color;  
     title.style.borderStyle = 'solid';  
     parent.appendChild(title);  
     var text = document.createTextNode(d.title);  
     title.appendChild(text);  
   });  
 }  




Well now, into the HTML page:



 <!DOCTYPE html>  
 <html lang="en">  
  <head>  
   [...]  
  </head>  
  <body>  
   [...]  
    <div class="row featurette">  
     <div class="col-md-7">  
      <div class="text_container">  
       <h2 class="featurette-heading">Language Skills<span class="text-muted"> - A mean of trasfer</span></h2>  
       <p class="lead">  
        To travel, to meet new culture, to understand the other point of view, to be sure that the message you drop is perceived in the proper way. Comunication is an amazing science.   
        <br>"Take advantage of every opportunity to practice your communication skills so that when important occasions arise, you will have the gift, the style, the sharpness, the clarity, and the emotions to affect other people." Jim Rohn</p>  
       <div class="legend" id="lang_legend"></div>  
      </div>  
     </div>  
     <div class="col-md-5">  
      <canvas id="lang_canvas" class="chart" width="600" height="450"></canvas>  
     </div>  
    </div>  
   [...]  
   <script src="js/Chart.js"></script>  
   <script src="js/legend.js"></script>  
   <script>  
   [...]  
   var chartData = [  
     {  
      value : 0.99999,  
      color : "#00FF00",   
      title : 'Italian - Native'  
     },  
     {  
      value : 0.95,  
      color : "#FF0000",   
      title : 'English - Fluent'  
     },  
     {  
      value : 0.9,  
      color : "#000000",   
      title : 'German - Fluent'  
     },  
     {  
      value : 0.7,  
      color : "#0000FF",   
      title : 'French - Good'  
     },  
     {  
      value : 0.4999,  
      color : "#FFFF00",   
      title : 'Spanish - Basics'  
     }  
    ];  
   var myPolarArea = new Chart(document.getElementById("lang_canvas").getContext("2d")).PolarArea(chartData);  
   legend(document.getElementById("lang_legend"), chartData);  
   </script>  
  </body>  
 </html>  



Please, note that I did not use fix numbers for the extreme values.
I mean that I did not give to english a value of 1 or to spanish a value of 0.5.

I think I found a small bug: giving such values, the library did not work properly (it was hiding spanish) and it was having such problem not only with such chart but also with other.

Anyway, not a big issue ;)
Globally the libraries are both very good!!!!