QuickTrip_for_JavaScript

JavaScript

See my HTML5 blog also

Firefox Firebug plugin shows error:

 "Blocked loading mixed active content..."

 To fix simply remove the http:// protocol prefixes like below:
  <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="MYContentPlaceHolderHead">  

  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" type="text/css" />


    <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>    

   <script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>    

   <script type="text/javascript" >        

    $(function () {            $(".datepicker").datepicker({ dateFormat: 'dd-M-yy' });        }); 

</script>       </asp:Content>


Ice Ice Baby

http://gamingjs.com/ice/

Automate with:

http://gruntjs.com/

Easy Graphs/charts

Easy pie graph (via html5 canvas with arcs)
<html><head>
<script src="17.js"></script>
</head><body onLoad="createPieGraph('pie1');createPieGraph('pie2');">
  <canvas id="pie1" width="300" height="300"
     pieSliceDegrees="10,10,10,330"
     pieSliceLabels="a,b,c,d"
     pieSliceColors="red,blue,green,yellow"
     ></canvas>
</body></html>

function createPieGraph(id){
     //id of canvas element w/attrs: pieSliceDegrees pieSliceLabels pieSliceColors
     var conElem= document.getElementById(id);
     var pieSliceLabelsCSV   =conElem.getAttribute("pieSliceLabels");
     var pieSliceLabelsArray =pieSliceLabelsCSV.split(',');
     var pieSliceColorsCSV   =conElem.getAttribute("pieSliceColors");
     var pieSliceColorsArray =pieSliceColorsCSV.split(',');
     var pieSliceDegreesCSV  =conElem.getAttribute("pieSliceDegrees");
     var pieSliceDegreesArray=pieSliceDegreesCSV.split(',').map(function(sliceDegree){return +sliceDegree;}); //convert strings to numbers

     if (conElem.getContext) var ctx=conElem.getContext('2d');
     var pie1=new PieGraph( conElem, ctx, {
     pieSliceDegreesArray: pieSliceDegreesArray,
     labels:               pieSliceLabelsArray,
     colors:               pieSliceColorsArray
     });
     pie1.draw();
}




function PieGraph(pCanvas, pContext, o){
    this.canvas = pCanvas;
        this.context= pContext;
    this.pieSliceDegreesArray = o.pieSliceDegreesArray //sum=360
    this.labels = o.labels;
    this.colors = o.colors;
}

PieGraph.prototype={
    draw: function(){//draw each segment
        for (var ii=0; ii<this.pieSliceDegreesArray.length; ii++) {
            this.drawSegment(ii, this.pieSliceDegreesArray[ii]);
        }
    },

    sumTo: function(pieSliceDegreesArray, idxx) {//simply find starting point in degrees for this next pieSlice
        var sum=0;
        for (var j=0; j<idxx; j++) {
            sum += pieSliceDegreesArray[j];
        }
        return sum;
    },

    drawSegment: function(idx, degrees){//simple arc, radius=canvaswidth/2
        this.context.save();
        var centerX = Math.floor(this.canvas.width / 2);
        var centerY = Math.floor(this.canvas.height / 2);
        radius = Math.floor(this.canvas.width / 2);

        var arcBeg=this.degreesToRadians(this.sumTo(this.pieSliceDegreesArray, idx));
        var arcRads=this.degreesToRadians(degrees);
        var arcEnd=arcBeg + arcRads;

        this.context.beginPath();
        this.context.moveTo(centerX, centerY);
        this.context.arc(centerX, centerY, radius, arcBeg, arcEnd, false);
        this.context.closePath();
        this.context.fillStyle=this.colors[idx];
        this.context.fill();
        this.context.restore();
        if (this.labels.length >idx) this.drawSegmentLabel(idx);
    },


    drawSegmentLabel: function(idx){//orient labels according to
        this.context.save();
        var x=Math.floor(this.canvas.width /2);
        var y=Math.floor(this.canvas.height /2);
        var angle;
        var angleD=this.sumTo(this.pieSliceDegreesArray, idx);
        var flip=(angleD<90 || angleD>270) ? false : true;

        this.context.translate(x, y);
        if(flip){
            angleD=angleD-180;
            this.context.textAlign = "left";
            angle=this.degreesToRadians(angleD);
            this.context.rotate(angle);
            this.context.translate(-(x + (this.canvas.width * 0.5))+15, -(this.canvas.height * 0.05)-10);
        }else{
            this.context.textAlign = "right";
            angle=this.degreesToRadians(angleD);
            this.context.rotate(angle);
        }
        var fontSize=Math.floor(this.canvas.height / 25);
        this.context.font=fontSize + "pt Helvetica";

        var dx=Math.floor(this.canvas.width * 0.5) - 10;
        var dy=Math.floor(this.canvas.height * 0.05);
        this.context.fillText(this.labels[idx], dx, dy);

        this.context.restore();
    },

    degreesToRadians: function(degreesOfThisSlice) {return (degreesOfThisSlice * Math.PI)/180;}
}

Simple jQuery date picker (uses doc.ready and also datepicker)

<html lang="en"><head>  <meta charset="utf-8">
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <script>
  $( document ).ready(function() {
 var monthNames=new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
 var curTime = new Date()
 var mmm =monthNames[curTime.getMonth()]
 var day = curTime.getDate()
 var year= curTime.getFullYear()
  $("p").text($("p").text()+ " Today is " +day+ "-"+mmm + "-" +year);
 $( "#dateStart" ).val(day+"-"+mmm+"-"+year);
 $( "#dateEnd" ).val(day+"-"+mmm+"-"+(year+1));
  });
  $(function() {
      $( ".datepicker" ).datepicker({ dateFormat: 'dd-M-yy' });
  });
</script></head>
<body><H1>Date Range</h1>
Start: <input type="text" id="dateStart" class="datepicker">
&nbsp; End:   <input type="text" id="dateEnd"   class="datepicker">
<p>Click to change a date above.</p>
</body></html>

Mouse-over html table cells with long text

coolstyle.css

table {
    white-space: nowrap;
}
td {
    display: inline-block;
    max-width: 50px;
    min-width: 50px;
    overflow: hidden;
    text-overflow: ellipsis;
    vertical-align: top;
    white-space: nowrap;
}
td:hover {
    text-overflow: clip;
    white-space: normal;
    word-break: break-all;
}

coolstyle.html

<html><head>
<link href="f_tablecellwrap.css" type="text/css" rel="stylesheet" />
</head><body>
<table>
    <tr>
        <td>blaaaa</td>
        <td>blaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</td>
        <td>blaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac. </td>   
        <td>blaaaa blaaaa blaaaaa</td>
        <td>blaaaa blaaaa blaaaaablaaaa blaaaa blaaaaablaaaa blaaaa blaaaaablaaaa blaaaa </td>
    </tr>
</table>
</body></html>

Add google site search to your site.

End resulting URL with queryString:
        https://www.google.com/search?q=cnc+site:trek4tech.blogspot.com

Upon Submit simply add the site info at the end of the users search qry/text field:

<!DOCTYPE html>
<html><body>
<form action="www.google.com" onsubmit="myFunction()">
  Enter name: <input type="text" name="q" id="Q">
  <input type="submit" value="Submit">
</form>

<script>
function myFunction() {
    alert("The form was submitted");
    var q=document.getElementById("Q").value;
 document.getElementById("Q").value=q+"+site:trek4tech.blogspot.com";
return true;
}
</script>
</body></html>

Mine/crawl thousands of sites

http://www.diffbot.com/pricing/
...a bit pricey however...



Move image on canvas
<html><head><title>Move image</title>
<script>
   var ctx,x=10, y=20,width=50, height=50,
   img=new Image();
   img.src = "LOGO.jpg"
   function init() {
        ctx =document.getElementById("canvas").getContext('2d');
        //initial drawing
        draw();
   }
   function draw(){
       ctx.drawImage(img,x,y,width,height);
   }
   function move(){
       ctx.clearRect(x,y,width,height);
       x = x+20;
       draw();
   }
</script></head><body onLoad="init();">
<input type="button"
value="Move &#10154;"
onclick="move()"/>

<canvas id="canvas" width="1200" height="1200">
    browser can't handle HTML5 canvas. Please get firefox or chrome.
</canvas>

<hr/>
http://animateyourhtml5.appspot.com/pres/index.html?lang=en#34

htmlGraphicLeftArrow="&#8678;",
htmlGraphicCircleArrow="&#8634;",
htmlGraphicUpArrow="&#8679;",
htmlGraphicDownArrow="&#8681;",
htmlGraphicLeftArrow2="&#8606;",
htmlGraphicleftArrow3="&#65513;",
htmlGraphicRightArrow="&#10154;",
htmlGraphicRightArrow2="&#8608;",
htmlGraphicRightArrow3="&#10148;",
htmlGraphicCrossBones="&#9760;",
htmlGraphicMagnifyingGlass="&#9740;",

</body></html>


Super Simple Server Side Ajax (Web 2.0)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script type="text/javascript">$(
  function(){
     $("#CELL1").click( 
         function(objEvent){
 $.ajax( 
{url:"SimpleGetServlet", type:"get", dataType:"html",
                  error: function(xhr, textStatus, errorThrown) {
                           alert('AjaxError Press F12 for Console.'); 
            console.log('xhr:');
            console.log(xhr);
            console.log('xhr.status:');
            console.log(xhr.status);
  console.log('xhr.responseText:');
console.log(xhr.responseText);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:' );
console.log(errorThrown);
                 },
                 beforeSend: function()        {$("#ajax-output2").html("AJAX-beforeSend()"); },
                 complete:   function()        {$("#ajax-output3").html("AJAX-complete()");   },
                 success:    function(strData) {$("#ajax-output4").html(strData);             }
                }
         );
         return( false ); // Prevent default click.
     }
   );
  }
);</script>
</head><body>
   <div id="CELL1">click me</div><br/>
<ul>
<li/>   <div id="ajax-output1"></div>
<li/>   <div id="ajax-output2"></div>
<li/>   <div id="ajax-output3"></div>
<li/>   <div id="ajax-output4"></div>
</ul>
</body></html>



=====================

package testAjax;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleGetServlet extends HttpServlet{
private static final long serialVersionUID=1L;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.getWriter().println("This is output from SimpleGet Servlet.");
res.getWriter().close();
}
}

==================================

Simple popup box based on mouse position (similar to a table cell "title")


<html><head>
<script>
function popup(e, idd) {
    var popup = document.getElementById('floating_popup');
    popup.style.display="block";
    popup.textContent = "hi";
    popup.style.top = e.clientY +10 + 'px';
    popup.style.left = (e.clientX +10) + 'px';
};
function popupHide(e, idd) {
    var popup = document.getElementById('floating_popup');
    popup.style.display="none";
};</script>
<style type="text/css">
#floating_popup {
    display: none;
    position:fixed;
    border: 2px solid black;
    padding: 5px;
}
</style>
</head><body>
  <table><tr><td id="xx" onmouseenter="popup(event, 'xx')" onmouseout="popupHide(event, 'xx')">
  Mouse enter shows popup, Mouse out hides it
 </td></tr></table>

  <span id="floating_popup"> </span>
</body></html>

Another cool cell title with graphics and line breaks

<td style="width:97%;background:RED;font-size:10px;" 
title="&#9830;1-oraserv&#013; 
  &#9830;Sid-Serial#:480-97&#013; 
  &#9830;CPU_Minutes:1.17&#013; 
  &#9830;Total_Minutes:6.267&#013; 
  &#9830;Disk_Reads:15495&#013; 
  &#9830;Program:JDBC Thin Client&#013; 
  &#9830;Executions:294988&#013; 
  &#9830;Schema:OWBEE" >

    <span style="font-size:18px;"> 

Set column width for table cell with specified header text in th

<html> <head>
<script>
function doIt() {
  var thCols=document.getElementsByTagName('th'), targetId;
  for (var i=0; i<thCols.length; ++i) {
     if (thCols[i].innerHTML == "mycolhdg1") {
        targetId = thCols[i].style.width = "500px";;
        break;
     }
  }
} </script>
</head> <body>
  <table>
     <tr> <th>mycolhdg1</th> </tr>
     <tr> <td bgcolor="blue">click to set this column to width of 500px</td> </tr>
  </table>
  <input type="button" value="cell" onclick="doIt()">
</body> </html>

Auto run a function without using body onload

<html><body">
self executing function placed at the @ bottom of html body surrounded by parenthesis!
<script>
(function() {
   alert('page loaded');
})();
</script>

</body></html>

Simple 2D array

<!DOCTYPE html><html lang="en"><head>
<script type="text/javascript">
function doIt(){
 var fMax=5; var jMax=3;
 var f=new Array();

 for(i=0;i<fMax;i++) {
    f[i]=new Array();
    for(j=0;j<jMax;j++) f[i][j]=i+j;
 }
 listAll(f, fMax, jMax);
}
function listAll(f, fMax, jMax){
 var outDiv=document.getElementById('OUTDIV');
 for(var Idx=0; Idx<fMax; Idx++){
      outDiv.innerHTML=outDiv.innerHTML+"<br/>";

     for(var barIdx=0; barIdx<jMax; barIdx++) {
  outDiv.innerHTML=outDiv.innerHTML+" "+f[Idx][barIdx];
  alert(f[Idx][barIdx]); 
    }

 }
}
</script></head>
<body onLoad="doIt();"><div id='OUTDIV'></div>
</body></html>


Simple setInterval ...repeats forever at ms interval

<!DOCTYPE html><html><head> <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script> var newX=0; function doIt(){ var incrVal=20; setInterval( function(){ if(newX>200) incrVal=incrVal*-1; if(newX<0) incrVal=incrVal*-1; newX=newX+incrVal; $('#rect1').attr('x', newX); $('#text1').attr('x', newX+20); $('#text1').text('x='+newX); }, 250); }</script> </head> <body onload='doIt();'> <h1>Simple setInterval ...repeats</h1> <svg width="90%" height="90%"> </g> <rect id="rect1" x="10" y="10" width="90" height="90" fill="lightblue" /> <text id="text1" x="30" y="50" ></text> </g> </svg> </body></html>

Simple SetTimeout (runs once after specified ms timer)

<!DOCTYPE html><html><head>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
 var newX=0;
 function doIt(){
    setTimeout(
      function(){ newX=newX+100;
        $('#rect1').attr('x', newX);    
        $('#text1').attr('x', newX+20); //keep text in center if rect
        $('#text1').text('x='+newX);    
    }, 1000);
}</script>
</head>
<body onload='doIt();'>
Simple/Sample setTimeout runs a js function after 1 second (1000 ms)
<svg width="90%" height="90%">
 </g>
   <rect id="rect1" x="10" y="10" width="90" height="90" fill="lightblue" />
   <text id="text1" x="30" y="50" >x=30 initially</text>
  </g>
</svg>

</body></html>

html javascript line continuation is sometimes the plus sign +

<span id='click_me'
onclick="document.getElementById('MyLabel').textContent='thank you for clicking'; +
 setTimeout(function(){alert('thanks');},2000);">
click me</span>

In a jsp page, it is the backslash "\"

         <td style='border:2px solid pink;'
              onmouseenter='showHelp("Should match 12C. totAmtPscs:${totAmtPscs_Formatted} \
              totMenAmtDss:${totMenAmtDss_Formatted} \
              totWomenAmtPscs:${totWomenAmtPscs_Formatted} \
              totWomenAmtDss:${totWomenAmtDss_Formatted}")'
              >

<fmt:formatNumber type="currency" value="${totMenAmtPscs
     + totMenAmtDss + totWomenAmtPscs + totWomenAmtDss}" />

</td>

call normal javascript function from inside jquery doc ready

 (also show how to use cookies and how to show querystring parms)

function fun2(msg) {
    alert(msg);
}
$(document).ready(function(){//jQuery

    var fun=function(msg){
        alert(msg);
    };
 
    fun('hifun');
    fun2('fun2');
    alert($.url().param('MEASURE_ID'));
    var first = $.cookies.get('FIRSTCOOKIE');
    if (first == undefined) {
        $.cookies.set('FIRSTCOOKIE', 'TRUE');  //first page load logic (tracked via cookies)
        $("#ctl00_pagecontent_STOPLIGHT_SPAN").show("slow"); //stoplight oper_n_vals
    } else {//subsequent page loads
        var measureAction = $.cookies.get('FIRSTCOOKIE');
        reqParmMeasureID = getParameterByName("MEASURE_ID_PARM");
        if (reqParmMeasureID == null || reqParmMeasureID == "") {
            $("#ctl00_pagecontent_GREENOPER").val("GE");
            $("#ctl00_pagecontent_YELLOWOPER").val("GE");
        }
    }
    /***********************************************
     * user typed into a decimalclass text field
     *   ...turn red if not numeric
     ***********************************************/
    $(".DECIMALCLASS").keypress(function (event) {
        return isNumber(event)
    });
    /***********************************************
     * count chars in text box
     ***********************************************/
    $('#ctl00_pagecontent_MEASURE_ALIAS_TEXTAREA').keyup(function () {
        var cs = $(this).val().length;
        $('#MEASURE_ALIAS_TEXTAREA_COUNT').text("current count " + cs);
    });
});

Super Simple HTML Radio Button 

<!DOCTYPE html><html><body> <h1>Radio Test</h1>

<form action="http://www.mytestsite17.com">
  <input type="radio" name="gender" value="male"> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other
  <input type='submit'>
</form>

<p>When a radio-button is clicked, all others w/same name become unchecked.</p>
<p>The submitted url and queryString will look like:
       http://www.mytestsite17.com/?gender=female</p>

</body></html>

Comments

Popular Posts