Run Javascript through a Firefox Bookmark to Highlight Components

Read <a href=’https://scottizu.wordpress.com/2014/10/31/executing-javascript-through-a-firefox-bookmark/’>Executing Javascript Through A Firefox Bookmark</a> to find out how to run javascript through a bookmark.

The modification from that page will allow you to store your BookmarkScript.js file in the root directory of Tomcat.  This is accessed in the Firefox Bookmark via:

http://localhost:8080/BookmarkScript.js

This code will highlight components whose id matches the string given. For instance, the following code will place an overlay on top of all div elements whose id starts with “abc_”.

This code needs to reside in the Root directory of your local Tomcat instance and be named as BookmarkScript.js.


// Print a message at the bottom of the page
err=function(e){
  s=e.description;
  if(!s){
    s=String(e);
  }
  d=document.createElement("div");
  d.innerHTML=s;
  d.style.color="red";
  document.body.appendChild(d);
  return d;
};
// Create an overlay above the placement
createOverlayDiv=function(e, zind){
  d=document.createElement("div");
  d.id=e.id+"_epo";
  d.name=e.name+"_epo";
  
  // Set style, width and height, top and left offset based off e
  d.style.cssText=e.style.cssText;
  d.style.width=e.clientWidth+"px";
  d.style.height=e.clientHeight+"px";
  d.style.top=e.offsetTop+"px";
  d.style.left=e.offsetLeft+"px";

  // Add extra overlay styling
  d.style.zIndex=zind;
  d.style.position="absolute";
  d.style.opacity = .5;
  d.style.display="block";
  d.style.textAlign="center";
  d.style.border="2px solid #A7A"; // Pink Outline
  d.style.background="#ADF"; // Blue Background
  
  // Set Minimum Width/Height and add text (undefined, auto, 0)
  w=e.clientWidth;
  if((!w)||((w!="auto")&&(w<150))){
	w=150;
	d.style.width="150px";
  }
  h=e.clientHeight;
  if((!h)||((h!="auto")&&(h<50))){
    h=50;
    d.style.height="50px";
  }
  d.innerHTML=d.id+"<br>"+w+" x "+h;
	
  return d;
}
// Highlights the placement by creating an overlay
highlighter=function(es, match){
  els=[];
  for(i=0;i<es.length;i++){
    e=es[i];
    if(e.id.indexOf(match)>-1){
      els.push(e);
    }
  }
  for(i=0;i<els.length;i++){
    e=els[i];
    d=createOverlayDiv(e, 10+i);
	e.parentNode.appendChild(d);
  }
};
err("Highlighter, Version 1.0");
err("Errors:");
err("").style.paddingTop="50px";
// Highlight Divs with Ids starting with abc_
try{
  highlighter(document.getElementsByTagName("div"), "abc_");
}catch(e){
  err(e);
}
Advertisements

A Simple Image Overlay Example

From jquerytools.org

This example uses jquery 1.2.7. Create a file “test.html” and edit with a text editor. Add the following code. You will need to add an image “myimage.png” to the same directory.


<html>
    <head>
        <meta charset="UTF-8" />
        <title>Image Overlay Example</title>
		<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>

	</head>
    <body>
<p>
	<button class="modalInput" rel="#myID">Show Image</button>
	<!-- yes/no dialog -->
	<div class="modal" id="myID" style="display:none;padding:15px;border:2px solid #333;-webkit-border-radius:6px;">
		<image src="myImage.png" />
		<br>
		<button class="close">Close</button>
	</div>
</p>

<script>
$(document).ready(function() {
	$(".modalInput").overlay({
		// some mask tweaks suitable for modal dialogs
		mask: {
			color: '#ebecff',
			loadSpeed: 200,
			opacity: 0.9
			},
		closeOnClick: false,
		fixed: false
	});
  });
</script>
    </body>
</html>

Real Time Visualization of an FFT

From www.smartjava.org

This code needs to be added to a Tomcat server to work. This allows the microphone in Chrome to be connected. See Real Time Visualization of Raw Sound from Microphone Input using HTML5.


<html>
<head>
<script type="text/javascript">

function canvasFillRect(leftX, topY, width, height) {
	var gradient = getCanvas().getContext('2d').createLinearGradient(0,0,0,300);
	gradient.addColorStop(1,'#000000');
	gradient.addColorStop(0.75,'#ff0000');
	gradient.addColorStop(0.25,'#ffff00');
	gradient.addColorStop(0,'#ffffff');
	getCanvas().getContext('2d').fillStyle=gradient;
	getCanvas().getContext('2d').fillRect(leftX, topY, width, height);
}

function canvasInitialize(width, height) {
	getCanvas().getContext('2d').strokeStyle='#000000';
	
	// Set canvas parameters
	getCanvas().width = width;
	getCanvas().height = height;

	// Outline
    getCanvas().getContext('2d').clearRect(0,0,width,height);
	getCanvas().getContext('2d').rect(0,0,width,height);
	getCanvas().getContext('2d').stroke();
}

function onSuccess(stream) {
	// stream -> mediaSource -> javascriptNode -> destination
    var context = new webkitAudioContext();
    var mediaStreamSource = context.createMediaStreamSource(stream);
	var analyser = context.createAnalyser();
    analyser.smoothingTimeConstant = 0.3;
    analyser.fftSize = 2048;
	var javascriptNode = context.createScriptProcessor(2048, 1, 1);
	mediaStreamSource.connect(analyser);
	analyser.connect(javascriptNode);
	javascriptNode.connect(context.destination);
	
	javascriptNode.onaudioprocess = createProcessBuffer(analyser);
}

function createProcessBuffer(analyser) {
	return function processBuffer() {
		var fftData =  new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(fftData);
		
		// clear canvas and draw border
		canvasInitialize(1024,500);
	
		var average = 0;
		for(var i=0; i<fftData.length; i++) {
			var sample = fftData[i];
			canvasFillRect(i*5, 250-sample, 3, sample);
			average = average + sample;
		}
		average = average/fftData.length;
		getLog().innerHTML = 'FFT Length:'+fftData.length + ' Average:' + average + '\n<br>';
	};
}

function onError() {
	alert('Error');
}

function getLog() {
	return document.getElementById('mylog');
}

function getCanvas() {
	return document.getElementById('mycanvas');
}	
  
function documentReady() {
	var dataObject = {video: false, audio: true}; // dataObject.video, dataObject.audio
	if(navigator.getUserMedia) {
        navigator.getUserMedia(dataObject, onSuccess, onError);
	} else if(navigator.webkitGetUserMedia) {
        navigator.webkitGetUserMedia(dataObject, onSuccess, onError);
	}
}
</script>
</head>
<body onload="documentReady();">
   <canvas id="mycanvas"></canvas>
   <div id="mylog"></div>
</body>
</html>

Visualizing Raw Data Samples from a Microphone

This code uses javascript to visualize mic data samples within Chrome.

This code must be deployed in a Web Server like Tomcat. See Real Time Visualization of Raw Sound from Microphone Input using HTML5.


<html>
<head>
<script type="text/javascript">
function canvasDrawLine(oPosX, oPosY, fPosX, fPosY) {
	var ctx = getCanvas().getContext('2d');
	ctx.beginPath();
	ctx.moveTo(oPosX, oPosY);
	ctx.lineTo(fPosX, fPosY);
	ctx.stroke();
}

function canvasDrawSquare(ulPosX, ulPosY, lrPosX, lrPosY) {
	canvasDrawLine(ulPosX, ulPosY, ulPosX, lrPosY);
	canvasDrawLine(ulPosX, lrPosY, lrPosX, lrPosY);
	canvasDrawLine(lrPosX, lrPosY, lrPosX, ulPosY);
	canvasDrawLine(lrPosX, ulPosY, ulPosX, ulPosY);
} 

function canvasInitialize(width, height) {
	// Set canvas parameters
	getCanvas().width = width;
	getCanvas().height = height;

	// Outline
    getCanvas().getContext('2d').clearRect(0,0,width,height);
	canvasDrawSquare(0,0,width,height);
}

function onSuccess(stream) {
	// stream -> mediaSource -> javascriptNode -> destination
    var context = new webkitAudioContext();
    var mediaStreamSource = context.createMediaStreamSource(stream);
	var javascriptNode = context.createScriptProcessor(2048, 1, 1);
	mediaStreamSource.connect(javascriptNode);
	javascriptNode.connect(context.destination);
	
	javascriptNode.onaudioprocess = processBuffer;
}

function processBuffer(e) {
	var micData = e.inputBuffer.getChannelData(0);
	
	// clear canvas and draw border
	getCanvas().getContext('2d').strokeStyle='#000000';
	canvasInitialize(1024,500);
	
	// draw samples values in green
	getCanvas().getContext('2d').strokeStyle='#00ff00';
	var average = 0;
	var gain = 100;
	for(var i=0; i<1024; i++) {
		var sample1 = micData[2*i];
		var sample2 = micData[2*i+1];
		var val = (sample1+sample2)*gain; // combine two samples and multiply by gain
		canvasDrawSquare(i, 250, i+1, 250-val);
		average = average + sample1*sample1 + sample2*sample2;
	}
	average = Math.sqrt(average);
	getLog().innerHTML = average + '\n<br>';
}

function onError() {
	alert('Error');
}

function getLog() {
	return document.getElementById('mylog');
}

function getCanvas() {
	return document.getElementById('mycanvas');
}	
  
function documentReady() {
	var dataObject = {video: false, audio: true}; // dataObject.video, dataObject.audio
	if(navigator.getUserMedia) {
        navigator.getUserMedia(dataObject, onSuccess, onError);
	} else if(navigator.webkitGetUserMedia) {
        navigator.webkitGetUserMedia(dataObject, onSuccess, onError);
	}
}
</script>
</head>
<body onload="documentReady();">
   <canvas id="mycanvas"></canvas>
   <div id="mylog"></div>
</body>
</html>

Functions as Variables in Javascript

Continued from Getting Started with Javascript.

In Javascript, functions may be assigned to variables. In fact, look at these three identity functions which all do essentially the same thing.

1. Create a variable ‘identity1’. Assign the value of ‘identity1’ as the identity function.

2. Create a variable ‘identity2’ and initialize its value to be the identity function.

3. Create a function ‘identity3’ (it isn’t clear, but ‘identity3’ is a variable.


<html>
<body>
<pre>
<script>
function log(arg) {
	document.body.innerHTML = document.body.innerHTML + arg + '\n<br>';
}
function clear() {
	document.body.innerHTML = '';
}
var identity1;
identity1 = function (x) {
	return x;
}

var identity2 = function(x) {
	return x;
}

function identity3(x) {
	return x;
}

log('First identity function:'+identity1('Hello World'));
log('Second identity function:'+identity2('Hello World'));
log('Third identity function:'+identity3('Hello World'));
</script>
</pre>
</body>
</html>

Getting Started with Javascript

Copy these contents into a file and name the file “test.html”. Then, open in a Web Browser like Internet Explorer or Google Chrome.


<html>
<body>
<pre>
<script>
function log(arg) {
	document.body.innerHTML = document.body.innerHTML + arg + '\n<br>';
}
log('Hello World');
</script>
</pre>
</body>
</html>

This code uses a javascript function which will write to the html file. You can also print other sentences to the screen. Here is another example which prints the results of multiple calls to an add function.

It also includes a function clear, if you want to clear the webpage. Try adding ‘clear();’ one of the lines after


<html>
<body>
<pre>
<script>
function log(arg) {
	document.body.innerHTML = document.body.innerHTML + arg + '\n<br>';
}
function clear() {
	document.body.innerHTML = '';
}
function add(x,y) {
	return x + y;
}
log('Hello World');
log('The sum of 3 and 4 is:'+add(3,4));
log('The sum of 5 and 8 is:'+add(5,8));
</script>
</pre>
</body>
</html>