JQUERY CODE EXAMPLE: Site with Non-Scrollable Scoreboard as Header
added on Oct 29, 2013
Site with Non-Scrollable Scoreboard as Header
This site shows a name and score in the header, body scrolls, when links are clicked anywhere, user sees his score change.

jQuery:
$(function() {
$('.hotlink').click(function() {
var elemScore = $('.thescore');
var score = parseInt(elemScore.html());
var newScore = score +1;
var strNewStore = padDigits(newScore, 5);
elemScore.html(strNewStore).css('color','navy').hide().fadeIn();
});
});
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
$('.hotlink').click(function() {
var elemScore = $('.thescore');
var score = parseInt(elemScore.html());
var newScore = score +1;
var strNewStore = padDigits(newScore, 5);
elemScore.html(strNewStore).css('color','navy').hide().fadeIn();
});
});
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
HTML/CSS:
<style type="text/css">
#site_topbanner {
position: fixed;
top: 0px;
width:100%;
height: 40px;
background-color:#eee;
margin:0;
padding:0;
border-bottom: 1px solid #ddd;
}
#site_topbanner .thename {
font-size: 29px;
float: left;
}
#site_topbanner .thescore {
font-size: 29px;
color: navy;
float: right;
}
#site_topbanner .site_topbanner_wrapper {
width: 600px;
margin-left: auto;
margin-right: auto;
}
#site_content {
width: 600px;
margin-left: auto;
margin-right: auto;
margin-top: 40px;
padding-top: 1px;
}
div.clear {
clear: both;
}
span.hotlink {
color:navy;
font-weight: bold;
cursor: pointer;
}
body {
margin:0;
padding:0;
}
</style>
<body>
<div id="site_topbanner">
<div class="site_topbanner_wrapper">
<div class="thename">The Name</div>
<div class="thescore">00345</div>
<div class="clear"></div>
</div>
</div>
<div id="site_content">...
#site_topbanner {
position: fixed;
top: 0px;
width:100%;
height: 40px;
background-color:#eee;
margin:0;
padding:0;
border-bottom: 1px solid #ddd;
}
#site_topbanner .thename {
font-size: 29px;
float: left;
}
#site_topbanner .thescore {
font-size: 29px;
color: navy;
float: right;
}
#site_topbanner .site_topbanner_wrapper {
width: 600px;
margin-left: auto;
margin-right: auto;
}
#site_content {
width: 600px;
margin-left: auto;
margin-right: auto;
margin-top: 40px;
padding-top: 1px;
}
div.clear {
clear: both;
}
span.hotlink {
color:navy;
font-weight: bold;
cursor: pointer;
}
body {
margin:0;
padding:0;
}
</style>
<body>
<div id="site_topbanner">
<div class="site_topbanner_wrapper">
<div class="thename">The Name</div>
<div class="thescore">00345</div>
<div class="clear"></div>
</div>
</div>
<div id="site_content">...
JQUERY CODE EXAMPLE: Basic code for flashcards using jquery widgets
added on Sep 8, 2013
Basic code for flashcards using jquery widgets
This code reads a list of flashcards from a text file and displays them as interactive flashcards which keep a score.

(function($){
$.widget("ui.itemFlashcard", {
options: {
elementId: null,
id: null,
front: null,
back: null
},
_create: function(){
//define
var that = this;
this.status = 'hiding';
this.backContentElem = $(this.element).find('.backContent');
this.backBlankElem = $(this.element).find('.backBlank');
//display
this.element.fadeIn();
//functionalize
this.element
.click(function(e) {
e.preventDefault();
if(that.status == 'showing') {
that.status = 'hiding';
that.backContentElem.hide();
that.backBlankElem.show();
} else {
that.status = 'showing';
that.backContentElem.show();
that.backBlankElem.hide();
$.post('process.php',
{
itemTypeIdCode: 'flashcards',
id: that.options.id,
action: 'viewed'
},
function( jsonString )
{
var data = $.parseJSON(jsonString);
});
$.event.trigger({
type: "scoreChange",
changeBy: 5
});
}
});
}
});
})(jQuery);
$.widget("ui.itemFlashcard", {
options: {
elementId: null,
id: null,
front: null,
back: null
},
_create: function(){
//define
var that = this;
this.status = 'hiding';
this.backContentElem = $(this.element).find('.backContent');
this.backBlankElem = $(this.element).find('.backBlank');
//display
this.element.fadeIn();
//functionalize
this.element
.click(function(e) {
e.preventDefault();
if(that.status == 'showing') {
that.status = 'hiding';
that.backContentElem.hide();
that.backBlankElem.show();
} else {
that.status = 'showing';
that.backContentElem.show();
that.backBlankElem.hide();
$.post('process.php',
{
itemTypeIdCode: 'flashcards',
id: that.options.id,
action: 'viewed'
},
function( jsonString )
{
var data = $.parseJSON(jsonString);
});
$.event.trigger({
type: "scoreChange",
changeBy: 5
});
}
});
}
});
})(jQuery);
REDBEAN CODE EXAMPLE: Basic code for SQLite access with Redbean
added on Sep 5, 2013
Basic code for SQLite access with Redbean
Uncomment out the following lines to see how you can read and write to an SQLite database.

//test_createBean();
//echo test_getSingleBean();
//echo test_getCountRecords();
//echo test_getMultipleBeansByIdList();
//test_executeQuery();
//echo test_getMultipleRecords();
//echo test_getMultipleRecordsWithParameterBindings();
//echo test_getSingleRecord();
//echo test_getSingleColumn();
//test_setColumnWithVariables();
test_createMultipleBeans();
R..close();
function test_createBean() {
$comparisonBean = R.dispense('comparisons');
$comparisonBean->categories = 'member,backbone';
$comparisonBean->whenCreated = '2013-05-31 04:30:06';
$comparisonBean->score = 23;
$comparisonBean->body = "Ember's sweet spot is applications where the user will keep the application open for long periods of time, perhaps all day, and interactions with the application's views or underlying data trigger deep changes in the view hierarchy. Ember is larger than Backbone, but thanks to Expires, Cache-Control this only matters on the the first load. After two days of daily use that extra 30k will be overshadowed by data transfers, sooner if your content involves images. Backbone apps focus more on brief or casual interactions, that are often just small sections of a larger static page: airbnb, Khan Academy, Foursquare's map and lists.";
R@@DOUBLE_SEMICOLONstore($comparisonBean);
}
function test_getSingleBean() {
$comparisonBean = R@@DOUBLE_SEMICOLONload('comparisons', 1);
echo $comparisonBean->body;
}
function test_getCountRecords() {
$r = '';
$r .= R@@DOUBLE_SEMICOLONcount('comparisons');
return $r;
}
function test_getMultipleBeansByIdList() {
$r = '';
$comparisons = R@@DOUBLE_SEMICOLONbatch('comparisons', [1, 2]);
if (count($comparisons) > 0) {
$r .= '<ul>';
foreach ($comparisons as $comparison) {
$r .= '<li>' . $comparison->body . '</li>';
}
$r .= '</ul>';
}
return $r;
}
function test_executeQuery() {
R@@DOUBLE_SEMICOLONexec('UPDATE comparisons SET categories="changed" WHERE id=2');
}
function test_getMultipleRecords() {
$r = '';
//$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE id>2');
$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE body LIKE "%javascript%"');
if (count($comparisonRecords) > 0) {
foreach ($comparisonRecords as $comparisonRecord) {
$r .= '<li><b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'] . '</li>';
}
}
return $r;
}
function test_getMultipleRecordsWithParameterBindings() {
$r = '';
$searchText = 'also';
$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE body LIKE :body', [':body'=>'%'.$searchText.'%']);
if (count($comparisonRecords) > 0) {
foreach ($comparisonRecords as $comparisonRecord) {
$r .= '<li><b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'] . '</li>';
}
}
return $r;
}
function test_getSingleRecord() {
$r = '';
$comparisonRecord = R@@DOUBLE_SEMICOLONgetRow('SELECT * FROM comparisons WHERE id=6');
$r .= '<b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'];
return $r;
}
function test_getSingleColumn() {
$r = '';
$ids = R@@DOUBLE_SEMICOLONgetCol('SELECT id FROM comparisons WHERE id > 3');
$r .= join($ids,',');
return $r;
}
function test_setColumnWithVariables() {
$id = 2;
$fieldName = 'body';
$fieldValue = 'the body was changed for record with id='.$id;
$comparisonBean = R@@DOUBLE_SEMICOLONload('comparisons', $id);
$comparisonBean->setAttr($fieldName, $fieldValue);
$idAffected = R@@DOUBLE_SEMICOLONstore($comparisonBean);
echo 'record with id '.$idAffected. ' changed';
}
function test_createMultipleBeans() {
$comparisonBeans = R@@DOUBLE_SEMICOLONdispense('comparisons',2);
if (count($comparisonBeans) > 0) {
foreach ($comparisonBeans as $comparisonBean) {
$comparisonBean->setAttr('categories', 'newone');
}
}
R@@DOUBLE_SEMICOLONstoreAll($comparisonBeans);
echo 'created';
}
//echo test_getSingleBean();
//echo test_getCountRecords();
//echo test_getMultipleBeansByIdList();
//test_executeQuery();
//echo test_getMultipleRecords();
//echo test_getMultipleRecordsWithParameterBindings();
//echo test_getSingleRecord();
//echo test_getSingleColumn();
//test_setColumnWithVariables();
test_createMultipleBeans();
R..close();
function test_createBean() {
$comparisonBean = R.dispense('comparisons');
$comparisonBean->categories = 'member,backbone';
$comparisonBean->whenCreated = '2013-05-31 04:30:06';
$comparisonBean->score = 23;
$comparisonBean->body = "Ember's sweet spot is applications where the user will keep the application open for long periods of time, perhaps all day, and interactions with the application's views or underlying data trigger deep changes in the view hierarchy. Ember is larger than Backbone, but thanks to Expires, Cache-Control this only matters on the the first load. After two days of daily use that extra 30k will be overshadowed by data transfers, sooner if your content involves images. Backbone apps focus more on brief or casual interactions, that are often just small sections of a larger static page: airbnb, Khan Academy, Foursquare's map and lists.";
R@@DOUBLE_SEMICOLONstore($comparisonBean);
}
function test_getSingleBean() {
$comparisonBean = R@@DOUBLE_SEMICOLONload('comparisons', 1);
echo $comparisonBean->body;
}
function test_getCountRecords() {
$r = '';
$r .= R@@DOUBLE_SEMICOLONcount('comparisons');
return $r;
}
function test_getMultipleBeansByIdList() {
$r = '';
$comparisons = R@@DOUBLE_SEMICOLONbatch('comparisons', [1, 2]);
if (count($comparisons) > 0) {
$r .= '<ul>';
foreach ($comparisons as $comparison) {
$r .= '<li>' . $comparison->body . '</li>';
}
$r .= '</ul>';
}
return $r;
}
function test_executeQuery() {
R@@DOUBLE_SEMICOLONexec('UPDATE comparisons SET categories="changed" WHERE id=2');
}
function test_getMultipleRecords() {
$r = '';
//$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE id>2');
$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE body LIKE "%javascript%"');
if (count($comparisonRecords) > 0) {
foreach ($comparisonRecords as $comparisonRecord) {
$r .= '<li><b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'] . '</li>';
}
}
return $r;
}
function test_getMultipleRecordsWithParameterBindings() {
$r = '';
$searchText = 'also';
$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE body LIKE :body', [':body'=>'%'.$searchText.'%']);
if (count($comparisonRecords) > 0) {
foreach ($comparisonRecords as $comparisonRecord) {
$r .= '<li><b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'] . '</li>';
}
}
return $r;
}
function test_getSingleRecord() {
$r = '';
$comparisonRecord = R@@DOUBLE_SEMICOLONgetRow('SELECT * FROM comparisons WHERE id=6');
$r .= '<b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'];
return $r;
}
function test_getSingleColumn() {
$r = '';
$ids = R@@DOUBLE_SEMICOLONgetCol('SELECT id FROM comparisons WHERE id > 3');
$r .= join($ids,',');
return $r;
}
function test_setColumnWithVariables() {
$id = 2;
$fieldName = 'body';
$fieldValue = 'the body was changed for record with id='.$id;
$comparisonBean = R@@DOUBLE_SEMICOLONload('comparisons', $id);
$comparisonBean->setAttr($fieldName, $fieldValue);
$idAffected = R@@DOUBLE_SEMICOLONstore($comparisonBean);
echo 'record with id '.$idAffected. ' changed';
}
function test_createMultipleBeans() {
$comparisonBeans = R@@DOUBLE_SEMICOLONdispense('comparisons',2);
if (count($comparisonBeans) > 0) {
foreach ($comparisonBeans as $comparisonBean) {
$comparisonBean->setAttr('categories', 'newone');
}
}
R@@DOUBLE_SEMICOLONstoreAll($comparisonBeans);
echo 'created';
}
JQUERY CODE EXAMPLE: Site with JQuery Page Switching and URL Rewriting
added on Jun 14, 2013
Site with JQuery Page Switching and URL Rewriting
This site contains everything you need to create a menu and "page area" with links which switch the page and also update the URL and page title.

index.php
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/jquery.history.js"></script>
<script src="js/jquery.getUrlParam.js"></script>
<script src="js/site.js"></script>
<link href="css/main.css" rel="stylesheet"/>
<script>
var CONFIG = {
pageIdCodes: [
'pageNews',
'pageEvents',
'pageInfo',
'pageCourses',
'pageHelp'],
pageTitles: [
'News',
'Events',
'Info',
'Courses',
'Help'
],
defaultPageIdCode: 'pageEvents'
};
$(document).ready(function() {
SITE.initialize();
});
function displayText(text) {
text = text === undefined ? 'defaultValue' : text;
console.log(text);
}
</script>
</head>
<body>
<ul id="nav">
</ul>
<div id="pageNews" class="pageArea">
<p>This is the news page which will have lots of news. This is the news page which will have lots of news. This is the news page which will have lots of news.</p>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<p>And more text.</p>
</div>
<div id="pageEvents" class="pageArea">
<p>This is the news page about all the events.</p>
<ul>
<li>Event #1</li>
<li>Event #2</li>
<li>Event #3</li>
</ul>
And here is a <a href="?page=pageNews">link to the news page</a>, which shows you that you can have both kinds of links: javascript and browser reload.
</div>
<div id="pageInfo" class="pageArea">This is the info page.</div>
<div id="pageCourses" class="pageArea">
<p>This is a page with all the list of courses on it.</p>
</div>
<div id="pageHelp" class="pageArea">This is the help page with lots of help.</div>
</body>
</html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/jquery.history.js"></script>
<script src="js/jquery.getUrlParam.js"></script>
<script src="js/site.js"></script>
<link href="css/main.css" rel="stylesheet"/>
<script>
var CONFIG = {
pageIdCodes: [
'pageNews',
'pageEvents',
'pageInfo',
'pageCourses',
'pageHelp'],
pageTitles: [
'News',
'Events',
'Info',
'Courses',
'Help'
],
defaultPageIdCode: 'pageEvents'
};
$(document).ready(function() {
SITE.initialize();
});
function displayText(text) {
text = text === undefined ? 'defaultValue' : text;
console.log(text);
}
</script>
</head>
<body>
<ul id="nav">
</ul>
<div id="pageNews" class="pageArea">
<p>This is the news page which will have lots of news. This is the news page which will have lots of news. This is the news page which will have lots of news.</p>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<p>And more text.</p>
</div>
<div id="pageEvents" class="pageArea">
<p>This is the news page about all the events.</p>
<ul>
<li>Event #1</li>
<li>Event #2</li>
<li>Event #3</li>
</ul>
And here is a <a href="?page=pageNews">link to the news page</a>, which shows you that you can have both kinds of links: javascript and browser reload.
</div>
<div id="pageInfo" class="pageArea">This is the info page.</div>
<div id="pageCourses" class="pageArea">
<p>This is a page with all the list of courses on it.</p>
</div>
<div id="pageHelp" class="pageArea">This is the help page with lots of help.</div>
</body>
</html>
site.js
var SITE = SITE || {};
SITE.initialize = function() {
var defaultPageIdCode;
var explicitPageIdCode;
var currentPageIdCode;
this.defineVariables = function() {
explicitPageIdCode = $(document).getUrlParam('page');
currentPageIdCode = this.isEmpty(explicitPageIdCode) ? CONFIG.defaultPageIdCode : explicitPageIdCode;
}
this.buildElements = function() {
for(var i = 0; i < CONFIG.pageIdCodes.length; i++) {
var pageIdCode = CONFIG.pageIdCodes[i];
var pageTitle = CONFIG.pageTitles[i];
$('ul#nav').append('<li class="navLink" data-id-code="'+pageIdCode+'">'+pageTitle+'</li>');
}
}
this.decorateElements = function() {
this.showCurrentPage(currentPageIdCode);
}
this.functionalizeElements = function() {
that = this;
$('li.navLink').click(function() {
var idCode = $(this).data('idCode');
that.showCurrentPage(idCode);
});
}
this.showCurrentPage = function(desiredPageIdCode) {
var r = '';
for(var i = 0; i < CONFIG.pageIdCodes.length; i++) {
var pageIdCode = CONFIG.pageIdCodes[i];
var elemPage = $('#'+pageIdCode);
var elemMenuLink = $('li.navLink[data-id-code="'+pageIdCode+'"]');
if(pageIdCode == desiredPageIdCode) {
elemPage.show();
elemMenuLink.addClass('selected');
} else {
elemPage.hide();
elemMenuLink.removeClass('selected');
}
}
this.updateUrl(desiredPageIdCode);
return r;
}
this.updateUrl = function(desiredPageIdCode) {
var urlPageIdCode = $(document).getUrlParam('page');
var currentPageIdCode = urlPageIdCode === null ? CONFIG.defaultPageIdCode : urlPageIdCode;
var finalPageIdCode = desiredPageIdCode === undefined ? currentPageIdCode : desiredPageIdCode;
History.replaceState({}, this.getTitleWithIdCode(finalPageIdCode), '?page='+finalPageIdCode);
}
this.getTitleWithIdCode = function(idCode) {
var index = CONFIG.pageIdCodes.indexOf(idCode);
return CONFIG.pageTitles[index];
}
this.isEmpty = function(value) {
if(value == '' || value == null) {
return true;
} else {
return false;
}
}
this.defineVariables();
this.buildElements();
this.decorateElements();
this.functionalizeElements();
}
SITE.initialize = function() {
var defaultPageIdCode;
var explicitPageIdCode;
var currentPageIdCode;
this.defineVariables = function() {
explicitPageIdCode = $(document).getUrlParam('page');
currentPageIdCode = this.isEmpty(explicitPageIdCode) ? CONFIG.defaultPageIdCode : explicitPageIdCode;
}
this.buildElements = function() {
for(var i = 0; i < CONFIG.pageIdCodes.length; i++) {
var pageIdCode = CONFIG.pageIdCodes[i];
var pageTitle = CONFIG.pageTitles[i];
$('ul#nav').append('<li class="navLink" data-id-code="'+pageIdCode+'">'+pageTitle+'</li>');
}
}
this.decorateElements = function() {
this.showCurrentPage(currentPageIdCode);
}
this.functionalizeElements = function() {
that = this;
$('li.navLink').click(function() {
var idCode = $(this).data('idCode');
that.showCurrentPage(idCode);
});
}
this.showCurrentPage = function(desiredPageIdCode) {
var r = '';
for(var i = 0; i < CONFIG.pageIdCodes.length; i++) {
var pageIdCode = CONFIG.pageIdCodes[i];
var elemPage = $('#'+pageIdCode);
var elemMenuLink = $('li.navLink[data-id-code="'+pageIdCode+'"]');
if(pageIdCode == desiredPageIdCode) {
elemPage.show();
elemMenuLink.addClass('selected');
} else {
elemPage.hide();
elemMenuLink.removeClass('selected');
}
}
this.updateUrl(desiredPageIdCode);
return r;
}
this.updateUrl = function(desiredPageIdCode) {
var urlPageIdCode = $(document).getUrlParam('page');
var currentPageIdCode = urlPageIdCode === null ? CONFIG.defaultPageIdCode : urlPageIdCode;
var finalPageIdCode = desiredPageIdCode === undefined ? currentPageIdCode : desiredPageIdCode;
History.replaceState({}, this.getTitleWithIdCode(finalPageIdCode), '?page='+finalPageIdCode);
}
this.getTitleWithIdCode = function(idCode) {
var index = CONFIG.pageIdCodes.indexOf(idCode);
return CONFIG.pageTitles[index];
}
this.isEmpty = function(value) {
if(value == '' || value == null) {
return true;
} else {
return false;
}
}
this.defineVariables();
this.buildElements();
this.decorateElements();
this.functionalizeElements();
}
PHP CODE EXAMPLE: How to roll your own PHP routing
added on Jun 12, 2013
How to roll your own PHP routing
This is an example of a PHP page using an .htaccess file to redirect all calls to the index.php file so that you can parse the URL the way you want. Not that all calls to css, js, and images have to be absolute.

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]
JQUERY CODE EXAMPLE: Simple and Smart Popups with PowerTip
added on Jun 7, 2013
Simple and Smart Popups with PowerTip
This powertip tool is lightweight and allows you to very easily make popup tips for e.g. titles where you don't have to specify a height. Notice the "smartPlacement: true" and that you have to have it in generally the right direction for this to work.

index.htm
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.powertip.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript" src="js/jquery.powertip.js"></script>
<script type="text/javascript">
$(function() {
// placement examples
$('#helpButton1').powerTip({placement: 's', smartPlacement: true});
$('#helpButton2').powerTip({placement: 'e', smartPlacement: true});
});
</script>
</head>
<body>
<input type="button" id="helpButton1" value="Help" title="Click this if you need technical help, otherwise ask your manager." />
<input type="button" id="helpButton2" value="Help" title="Click this if you need technical help, otherwise ask your manager." />
</body>
</html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.powertip.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript" src="js/jquery.powertip.js"></script>
<script type="text/javascript">
$(function() {
// placement examples
$('#helpButton1').powerTip({placement: 's', smartPlacement: true});
$('#helpButton2').powerTip({placement: 'e', smartPlacement: true});
});
</script>
</head>
<body>
<input type="button" id="helpButton1" value="Help" title="Click this if you need technical help, otherwise ask your manager." />
<input type="button" id="helpButton2" value="Help" title="Click this if you need technical help, otherwise ask your manager." />
</body>
</html>
JQUERY CODE EXAMPLE: JQueryUI Radio Buttons
added on Jun 4, 2013
JQueryUI Radio Buttons
This shows how to use the JQueryUI radio buttons.

index.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Button - Radios</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$("#displayKind" ).buttonset();
$("input#displayKindFullText").click(function() {
$('div#message').html('this is the full text');
});
$("input#displayKindGuessBlanks").click(function() {
$('div#message').html('this is the text as with blanks to guess the words')
});
$("input#displayKindFullText").click();
});
</script>
</head>
<body>
<form>
<div id="displayKind" style="font-size: 8pt">
<input type="radio" id="displayKindFullText" name="radio" checked="checked" /><label for="displayKindFullText">Full Text</label>
<input type="radio" id="displayKindGuessBlanks" name="radio" /><label for="displayKindGuessBlanks">Guess Blanks</label>
</div>
<div id="message" style="margin:10px"></div>
</form>
</body>
</html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Button - Radios</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$("#displayKind" ).buttonset();
$("input#displayKindFullText").click(function() {
$('div#message').html('this is the full text');
});
$("input#displayKindGuessBlanks").click(function() {
$('div#message').html('this is the text as with blanks to guess the words')
});
$("input#displayKindFullText").click();
});
</script>
</head>
<body>
<form>
<div id="displayKind" style="font-size: 8pt">
<input type="radio" id="displayKindFullText" name="radio" checked="checked" /><label for="displayKindFullText">Full Text</label>
<input type="radio" id="displayKindGuessBlanks" name="radio" /><label for="displayKindGuessBlanks">Guess Blanks</label>
</div>
<div id="message" style="margin:10px"></div>
</form>
</body>
</html>
BOOSTRAP CODE EXAMPLE: Basic, Interactive Bootstrap Site
added on May 30, 2013
Basic, Interactive Bootstrap Site
This is a site that is based on bootstrap (CSS file) and had jQuery added to it so that the menus are interactive.

html
<!DOCTYPE html>
<head>
<title>btest</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/site.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="container">
<h1>The Title</h1>
<div class='navbar navbar-inverse'>
<div class='navbar-inner nav-collapse' style="height: auto;">
<ul class="nav">
<li id="linkHome" class="active"><a href="#">Home</a></li>
<li id="linkInfo"><a href="#">Info</a></li>
<li id="linkAbout"><a href="#">About</a></li>
</ul>
</div>
</div>
<div id='content' class='row-fluid'>
<div class='span9 main'>
<div class="sitePage" id="pageHome">
<h2>Home</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageInfo">
<h2>Info</h2>
<p>N...</p>
</div>
<div class="sitePage" id="pageAbout">
<h2>About</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection1">
<h2>Nation States at the End of the 19th Century</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection2">
<h2>1880-1910: Technological Inventions</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection3">
<h2>Late 19th Century Japan</h2>
<p>...</p>
</div>
</div>
<div class='span3 sidebar'>
<ul class="nav nav-tabs nav-stacked">
<li><a id="linkSection1" class="sideLink" href='#'>Nation States at the End of the 19th Century</a></li>
<li><a id="linkSection2" class="sideLink" href='#'>1880-1910: Technological Inventions</a></li>
<li><a id="linkSection3" class="sideLink" href='#'>Late 19th Century Japan</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>
<head>
<title>btest</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/site.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="container">
<h1>The Title</h1>
<div class='navbar navbar-inverse'>
<div class='navbar-inner nav-collapse' style="height: auto;">
<ul class="nav">
<li id="linkHome" class="active"><a href="#">Home</a></li>
<li id="linkInfo"><a href="#">Info</a></li>
<li id="linkAbout"><a href="#">About</a></li>
</ul>
</div>
</div>
<div id='content' class='row-fluid'>
<div class='span9 main'>
<div class="sitePage" id="pageHome">
<h2>Home</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageInfo">
<h2>Info</h2>
<p>N...</p>
</div>
<div class="sitePage" id="pageAbout">
<h2>About</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection1">
<h2>Nation States at the End of the 19th Century</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection2">
<h2>1880-1910: Technological Inventions</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection3">
<h2>Late 19th Century Japan</h2>
<p>...</p>
</div>
</div>
<div class='span3 sidebar'>
<ul class="nav nav-tabs nav-stacked">
<li><a id="linkSection1" class="sideLink" href='#'>Nation States at the End of the 19th Century</a></li>
<li><a id="linkSection2" class="sideLink" href='#'>1880-1910: Technological Inventions</a></li>
<li><a id="linkSection3" class="sideLink" href='#'>Late 19th Century Japan</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>
site.js
var SITE = SITE || {};
SITE.initialize = function() {
var fadeTime = 100;
that = this;
$('li#linkHome').click(function() {
resetPageLinks();
$('li#linkHome').addClass('active');
resetPages();
$('div#pageHome').fadeIn(fadeTime);
});
$('li#linkInfo').click(function() {
resetPageLinks();
$('li#linkInfo').addClass('active');
resetPages();
$('div#pageInfo').fadeIn(fadeTime);
});
$('li#linkAbout').click(function() {
resetPageLinks();
$('li#linkAbout').addClass('active');
resetPages();
$('div#pageAbout').fadeIn(fadeTime);
});
$('a#linkSection1').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection1').fadeIn(fadeTime);
markSideLink(this);
});
$('a#linkSection2').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection2').fadeIn(fadeTime);
markSideLink(this);
});
$('a#linkSection3').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection3').fadeIn(fadeTime);
markSideLink(this);
});
function resetPageLinks() {
$('ul.nav li').removeClass('active');
$('a.sideLink').css('font-weight','normal');
}
function resetPages() {
$('div.sitePage').hide();
}
function markSideLink(elem) {
$(elem).css('font-weight', 'bold');
}
}
SITE.initialize = function() {
var fadeTime = 100;
that = this;
$('li#linkHome').click(function() {
resetPageLinks();
$('li#linkHome').addClass('active');
resetPages();
$('div#pageHome').fadeIn(fadeTime);
});
$('li#linkInfo').click(function() {
resetPageLinks();
$('li#linkInfo').addClass('active');
resetPages();
$('div#pageInfo').fadeIn(fadeTime);
});
$('li#linkAbout').click(function() {
resetPageLinks();
$('li#linkAbout').addClass('active');
resetPages();
$('div#pageAbout').fadeIn(fadeTime);
});
$('a#linkSection1').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection1').fadeIn(fadeTime);
markSideLink(this);
});
$('a#linkSection2').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection2').fadeIn(fadeTime);
markSideLink(this);
});
$('a#linkSection3').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection3').fadeIn(fadeTime);
markSideLink(this);
});
function resetPageLinks() {
$('ul.nav li').removeClass('active');
$('a.sideLink').css('font-weight','normal');
}
function resetPages() {
$('div.sitePage').hide();
}
function markSideLink(elem) {
$(elem).css('font-weight', 'bold');
}
}
KNOCKOUT CODE EXAMPLE: Knockout list adding
added on May 27, 2013
Knockout list adding
index.htm
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/main.css"/>
<script src="js/jquery-1.10.0.js"></script>
<script src="js/knockout-2.2.1.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="formWrapper">
<form data-bind="submit: addItem">
New Item:
<input id="itemToAdd" data-bind="value:itemToAdd, valueUpdate: 'afterkeydown'">
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
<p style="margin: 10px 0 10px 0">Your items:</p>
<select multiple="multiple" style="width:200px;height:300px" data-bind="options: items"></select>
</form>
</div>
</body>
</html>
<html>
<head>
<link rel="stylesheet" href="css/main.css"/>
<script src="js/jquery-1.10.0.js"></script>
<script src="js/knockout-2.2.1.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="formWrapper">
<form data-bind="submit: addItem">
New Item:
<input id="itemToAdd" data-bind="value:itemToAdd, valueUpdate: 'afterkeydown'">
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
<p style="margin: 10px 0 10px 0">Your items:</p>
<select multiple="multiple" style="width:200px;height:300px" data-bind="options: items"></select>
</form>
</div>
</body>
</html>

main.js
var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
initForm();
}
}.bind(this);
};
function initForm() {
$('#itemToAdd').focus();
}
$(document).ready(function() {
initForm();
ko.applyBindings(new SimpleListModel(["German", "French", "English"]));
});
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
initForm();
}
}.bind(this);
};
function initForm() {
$('#itemToAdd').focus();
}
$(document).ready(function() {
initForm();
ko.applyBindings(new SimpleListModel(["German", "French", "English"]));
});
JQUERY CODE EXAMPLE: Nice, cascading fade-in of multiple items
added on May 23, 2013
Nice, cascading fade-in of multiple items
This simple effect is produce with various length fades and different shades of a color.

index.html
<!DOCTYPE>
<html>
<link rel="stylesheet" href="css/main.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(init);
function init() {
$('.showArea .course1').fadeIn(500);
$('.showArea .course2').fadeIn(1000);
$('.showArea .course3').fadeIn(1500);
$('.showArea .course4').fadeIn(2000);
};
</script>
<body>
<div class="showArea">
<div class="course1">Course #1</div>
<div class="course2">Course #2</div>
<div class="course3">Course #3</div>
<div class="course4">Course #4</div>
</div>
</body>
</html>
<html>
<link rel="stylesheet" href="css/main.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(init);
function init() {
$('.showArea .course1').fadeIn(500);
$('.showArea .course2').fadeIn(1000);
$('.showArea .course3').fadeIn(1500);
$('.showArea .course4').fadeIn(2000);
};
</script>
<body>
<div class="showArea">
<div class="course1">Course #1</div>
<div class="course2">Course #2</div>
<div class="course3">Course #3</div>
<div class="course4">Course #4</div>
</div>
</body>
</html>
main.css
.showArea div {
width: 300px;
height: 50px;
margin: 0 0 5px 5px;
padding: 10px;
display: none;
}
.showArea .course1 {
background-color: #eee;
}
.showArea .course2 {
background-color: #ddd;
}
.showArea .course3 {
background-color: #ccc;
}
.showArea .course4 {
background-color: #bbb;
}
width: 300px;
height: 50px;
margin: 0 0 5px 5px;
padding: 10px;
display: none;
}
.showArea .course1 {
background-color: #eee;
}
.showArea .course2 {
background-color: #ddd;
}
.showArea .course3 {
background-color: #ccc;
}
.showArea .course4 {
background-color: #bbb;
}
JQUERY CODE EXAMPLE: Flashcard example with clicks
added on May 23, 2013
Flashcard example with clicks
This shows how to use mouseenter, mousedown and a right click to affect a flashcard-like interaction.
(no image found with Id-Code = "jqueryClicks")
index.html
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.3.custom.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body oncontextmenu="return false;">
<div class="learnItem">
<div class="areaShow"></div>
<div class="areaHelp"></div>
<div class="clear"></div>
</div>
</body>
</html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.3.custom.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body oncontextmenu="return false;">
<div class="learnItem">
<div class="areaShow"></div>
<div class="areaHelp"></div>
<div class="clear"></div>
</div>
</body>
</html>
main.js
$(document).ready(function() {
$('div.areaShow').html('asdkfsdfj').fadeIn(3000);
$('div.areaShow').css({
'cursor':'pointer'
}).mousedown(function(e) {
if(e.which === 3) {
e.preventDefault();
$('div.areaHelp').html('Answer.');
$('div.areaHelp').data('status','answer');
$(this).hide(1000);
}
});
$('div.areaShow').mouseenter(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #1');
}
});
$('div.areaShow').mouseleave(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('');
}
});
$('div.areaShow').mousedown(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #2');
}
});
$('div.areaShow').mouseup(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #1');
}
});
});
$('div.areaShow').html('asdkfsdfj').fadeIn(3000);
$('div.areaShow').css({
'cursor':'pointer'
}).mousedown(function(e) {
if(e.which === 3) {
e.preventDefault();
$('div.areaHelp').html('Answer.');
$('div.areaHelp').data('status','answer');
$(this).hide(1000);
}
});
$('div.areaShow').mouseenter(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #1');
}
});
$('div.areaShow').mouseleave(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('');
}
});
$('div.areaShow').mousedown(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #2');
}
});
$('div.areaShow').mouseup(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #1');
}
});
});
KNOCKOUTJS CODE EXAMPLE: Knockout.js Button Click and Counter
added on May 21, 2013
Knockout.js Button Click and Counter
This is an example of showing hints by clicking a button, and when user has seen enough, button is disabled and can be reset.

index.htm
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/knockout-2.2.1.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div>You've seen <span data-bind="text: numberOfHints"></span> hints.</div>
<button data-bind="click: processHint, disable: hasShownAllHints">Show Hint</button>
<div id="hintArea"></div>
<div data-bind="visible: hasShownAllHints">
You have shown all hints. <span class="pseudoLink" data-bind="click:resetHints">reset</a>
</div>
</body>
</html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/knockout-2.2.1.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div>You've seen <span data-bind="text: numberOfHints"></span> hints.</div>
<button data-bind="click: processHint, disable: hasShownAllHints">Show Hint</button>
<div id="hintArea"></div>
<div data-bind="visible: hasShownAllHints">
You have shown all hints. <span class="pseudoLink" data-bind="click:resetHints">reset</a>
</div>
</body>
</html>
main.js
var hintViewModel = function() {
this.numberOfHints = ko.observable(0);
this.hints = ['first hint', 'second hint', 'third hint'];
this.processHint = function() {
this.numberOfHints(this.numberOfHints() + 1);
$('#hintArea').html(this.hints[this.numberOfHints()-1]);
};
this.resetHints = function() {
this.numberOfHints(0);
$('#hintArea').html('');
};
this.hasShownAllHints = ko.computed(function() {
return this.numberOfHints() >= 3;
}, this);
};
$(document).ready(init);
function init() {
ko.applyBindings(new hintViewModel());
}
this.numberOfHints = ko.observable(0);
this.hints = ['first hint', 'second hint', 'third hint'];
this.processHint = function() {
this.numberOfHints(this.numberOfHints() + 1);
$('#hintArea').html(this.hints[this.numberOfHints()-1]);
};
this.resetHints = function() {
this.numberOfHints(0);
$('#hintArea').html('');
};
this.hasShownAllHints = ko.computed(function() {
return this.numberOfHints() >= 3;
}, this);
};
$(document).ready(init);
function init() {
ko.applyBindings(new hintViewModel());
}
KNOCKOUTJS CODE EXAMPLE: Hello World knockout.js
added on May 21, 2013
Hello World knockout.js
index.htm
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/knockout-2.2.1.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<p>First Name: <input data-bind="value:firstName"/></p>
<p>Last Name: <input data-bind="value:lastName"/></p>
<p>Hello, <span data-bind="text:fullName"></span></p>
</body>
</html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/knockout-2.2.1.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<p>First Name: <input data-bind="value:firstName"/></p>
<p>Last Name: <input data-bind="value:lastName"/></p>
<p>Hello, <span data-bind="text:fullName"></span></p>
</body>
</html>

main.js
var ViewModel = function(p_firstName, p_lastName) {
this.firstName = ko.observable(p_firstName);
this.lastName = ko.observable(p_lastName);
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
};
$(document).ready(function() {
ko.applyBindings(new ViewModel('Jim', 'Smith'));
});
this.firstName = ko.observable(p_firstName);
this.lastName = ko.observable(p_lastName);
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
};
$(document).ready(function() {
ko.applyBindings(new ViewModel('Jim', 'Smith'));
});
PHP CODE EXAMPLE: A PHP script that observes another and kills is process if it hangs
added on Feb 5, 2013
A PHP script that observes another and kills is process if it hangs
If you have a PHP script running on a linux server which hangs now and then, this is an example of a script that can observe that script and when it hangs, kills it, so the cronjob can restart it.

test.ThatHangs.php
class TestThatHangs {
protected $keepalive_file_name = 'test_keepalive_info.txt';
protected $test_phase = self:nnn:TESTPHASE_HANG;
protected $number_of_seconds_to_run_before_hang = 10;
const TESTPHASE_HANG = 1;
const TESTPHASE_EXITCORRECTLY = 2;
public function process() {
$this->_createKeepAliveFile();
$this->_display('started script');
for ($index = 0; $index < $this->number_of_seconds_to_run_before_hang; $index++) {
$this->_display('test output');
sleep(1);
$this->_touchKeepAliveFile();
}
if ($this->test_phase == self:nnn:TESTPHASE_HANG) {
$this->_emulateHang();
} else {
$this->_exitCorrectly();
}
}
protected function _exitCorrectly() {
$this->_cleanUpKeepAliveFile();
$this->_display('exited correctly');
exit;
}
protected function _emulateHang() {
$this->_display('emulating hang...');
sleep(10000);
}
protected function _display($text) {
echo $text . PHP_EOL;
}
protected function _touchKeepAliveFile() {
touch($this->keepalive_file_name);
}
protected function _getKeepAliveFileLastTouchedAbsoluteSeconds() {
clearstatcache();
return filemtime($this->keepalive_file_name);
}
protected function _createKeepAliveFile() {
file_put_contents($this->keepalive_file_name, getmypid());
}
protected function _cleanUpKeepAliveFile() {
unlink($this->keepalive_file_name);
}
protected function _getCurrentAbsoluteSeconds() {
return strtotime(date("Y-m-d H:i:s"));
}
}
$testThatHangs = new TestThatHangs();
$testThatHangs->process();
protected $keepalive_file_name = 'test_keepalive_info.txt';
protected $test_phase = self:nnn:TESTPHASE_HANG;
protected $number_of_seconds_to_run_before_hang = 10;
const TESTPHASE_HANG = 1;
const TESTPHASE_EXITCORRECTLY = 2;
public function process() {
$this->_createKeepAliveFile();
$this->_display('started script');
for ($index = 0; $index < $this->number_of_seconds_to_run_before_hang; $index++) {
$this->_display('test output');
sleep(1);
$this->_touchKeepAliveFile();
}
if ($this->test_phase == self:nnn:TESTPHASE_HANG) {
$this->_emulateHang();
} else {
$this->_exitCorrectly();
}
}
protected function _exitCorrectly() {
$this->_cleanUpKeepAliveFile();
$this->_display('exited correctly');
exit;
}
protected function _emulateHang() {
$this->_display('emulating hang...');
sleep(10000);
}
protected function _display($text) {
echo $text . PHP_EOL;
}
protected function _touchKeepAliveFile() {
touch($this->keepalive_file_name);
}
protected function _getKeepAliveFileLastTouchedAbsoluteSeconds() {
clearstatcache();
return filemtime($this->keepalive_file_name);
}
protected function _createKeepAliveFile() {
file_put_contents($this->keepalive_file_name, getmypid());
}
protected function _cleanUpKeepAliveFile() {
unlink($this->keepalive_file_name);
}
protected function _getCurrentAbsoluteSeconds() {
return strtotime(date("Y-m-d H:i:s"));
}
}
$testThatHangs = new TestThatHangs();
$testThatHangs->process();
testKeepAlive.php
class TestKeepAlive {
protected $seconds_of_nonactivity_to_kill_script = 10;
protected $keepalive_file_name = 'test_keepalive_info.txt';
public function process() {
$this->_display('keep alive script is observing keepalive file...');
while (true) {
sleep(1);
$keepAliveFileLastTouchedAbsoluteSeconds = $this->_getKeepAliveFileLastTouchedAbsoluteSeconds();
if ($keepAliveFileLastTouchedAbsoluteSeconds == 0) {
$this->_display('the script is not running');
} else {
$currentAbsoluteSeconds = $this->_getCurrentAbsoluteSeconds();
$touchedAgoSeconds = $currentAbsoluteSeconds - $keepAliveFileLastTouchedAbsoluteSeconds;
$this->_display('script is running and keep alive file was touched ' . $touchedAgoSeconds . ' seconds ago');
if($touchedAgoSeconds >= $this->seconds_of_nonactivity_to_kill_script) {
$this->_killProcess();
}
}
}
}
protected function _display($text) {
echo $text . PHP_EOL;
}
protected function _getKeepAliveFileLastTouchedAbsoluteSeconds() {
if (!file_exists($this->keepalive_file_name)) {
return 0;
} else {
clearstatcache();
return filemtime($this->keepalive_file_name);
}
}
protected function _getCurrentAbsoluteSeconds() {
return strtotime(date("Y-m-d H:i:s"));
}
protected function _cleanUpKeepAliveFile() {
unlink($this->keepalive_file_name);
}
protected function _getProcessId() {
$lines = file($this->keepalive_file_name);
if(count($lines) > 0) {
return intval($lines[0]);
} else {
return 0;
}
}
protected function _killProcess() {
$processId = $this->_getProcessId();
$this->_display('killing process ' . $processId);
exec("kill $processId");
$this->_cleanUpKeepAliveFile();
}
}
$testKeepAlive = new TestKeepAlive();
$testKeepAlive->process();
protected $seconds_of_nonactivity_to_kill_script = 10;
protected $keepalive_file_name = 'test_keepalive_info.txt';
public function process() {
$this->_display('keep alive script is observing keepalive file...');
while (true) {
sleep(1);
$keepAliveFileLastTouchedAbsoluteSeconds = $this->_getKeepAliveFileLastTouchedAbsoluteSeconds();
if ($keepAliveFileLastTouchedAbsoluteSeconds == 0) {
$this->_display('the script is not running');
} else {
$currentAbsoluteSeconds = $this->_getCurrentAbsoluteSeconds();
$touchedAgoSeconds = $currentAbsoluteSeconds - $keepAliveFileLastTouchedAbsoluteSeconds;
$this->_display('script is running and keep alive file was touched ' . $touchedAgoSeconds . ' seconds ago');
if($touchedAgoSeconds >= $this->seconds_of_nonactivity_to_kill_script) {
$this->_killProcess();
}
}
}
}
protected function _display($text) {
echo $text . PHP_EOL;
}
protected function _getKeepAliveFileLastTouchedAbsoluteSeconds() {
if (!file_exists($this->keepalive_file_name)) {
return 0;
} else {
clearstatcache();
return filemtime($this->keepalive_file_name);
}
}
protected function _getCurrentAbsoluteSeconds() {
return strtotime(date("Y-m-d H:i:s"));
}
protected function _cleanUpKeepAliveFile() {
unlink($this->keepalive_file_name);
}
protected function _getProcessId() {
$lines = file($this->keepalive_file_name);
if(count($lines) > 0) {
return intval($lines[0]);
} else {
return 0;
}
}
protected function _killProcess() {
$processId = $this->_getProcessId();
$this->_display('killing process ' . $processId);
exec("kill $processId");
$this->_cleanUpKeepAliveFile();
}
}
$testKeepAlive = new TestKeepAlive();
$testKeepAlive->process();
run.sh
DIR=$( cd "$( dirname "$0" )" && pwd )
cd $DIR
if ps ax | grep "$1" | grep -v grep | grep -v "/bin/sh" > /dev/null
then
echo ""
else
php $1 $2 $3 $4 $5 $6
fi
cd $DIR
if ps ax | grep "$1" | grep -v grep | grep -v "/bin/sh" > /dev/null
then
echo ""
else
php $1 $2 $3 $4 $5 $6
fi
cronjobs (crontab -e)
MAILTO="test@company.com"
#* * * * * ~/work/testing/run.sh testThatHangs.php >> /var/log/cronjobs/log_testThatHangs
#* * * * * ~/work/testing/run.sh testKeepAlive.php >> /var/log/cronjobs/log_testKeepAlive
#* * * * * ~/work/testing/run.sh testThatHangs.php >> /var/log/cronjobs/log_testThatHangs
#* * * * * ~/work/testing/run.sh testKeepAlive.php >> /var/log/cronjobs/log_testKeepAlive
(replace :nnn: with two colons)
JQUERY CODE EXAMPLE: List of elements with similar functionality
added on Jan 30, 2013
List of elements with similar functionality
Shows how to create a list of elements, each with a unique id, each element with similar funtionality.

<html>
<head>
<script type="text/javascript" src="systemJavascript/jquery-1.8.3.min.js"></script>
</head>
<body>
<div id="infoItem_123" class="infoItem">
<div class="menu">
<span class="menuOne">one</span>
<span class="menuTwo">two</span>
</div>
<div class="content">intro message</div>
<div class="contentOne">you clicked one</div>
<div class="contentTwo">you clicked two</div>
</div>
<div id="infoItem_456" class="infoItem">
<div class="menu">
<span class="menuOne">eins</span>
<span class="menuTwo">zwei</span>
</div>
<div class="content">Introtext</div>
<div class="contentOne">du hast auf eins geklickt</div>
<div class="contentTwo">du hast auf zwei geklickt</div>
</div>
</body>
</html>
<script type="text/javascript">
var INFOITEM = INFOITEM || {};
INFOITEM.initialize = function(infoItem) {
var elemMenuOne;
var elemMenuTwo;
var elemContent;
var elemContentOne;
var elemContentTwo;
var itemId;
this.defineVariables = function() {
elemMenuOne = infoItem.find('.menuOne');
elemMenuTwo = infoItem.find('.menuTwo');
elemContent = infoItem.find('.content');
elemContentOne = infoItem.find('.contentOne');
elemContentTwo = infoItem.find('.contentTwo');
itemId = infoItem.attr('id');
}
this.decorateElements = function() {
elemMenuOne.css('background-color', 'beige');
this.decorateAsLink(elemMenuOne);
elemMenuTwo.css('background-color', 'beige');
this.decorateAsLink(elemMenuTwo);
elemContentOne.hide();
elemContentTwo.hide();
}
this.functionalizeElements = function() {
that = this;
elemMenuOne.click(function(e) {
that.displayText($('#'+itemId), elemContentOne.html());
});
elemMenuTwo.click(function(e) {
that.displayText($('#'+itemId), elemContentTwo.html());
});
}
this.displayText = function(clickedInfoItem, text) {
clickedInfoItem.find('.content').html(text);
}
this.decorateAsLink = function(elem) {
elem.css({
'cursor' :'pointer',
'text-decoration' : 'underline',
'font-weight' : 'normal'
});
}
this.defineVariables();
this.decorateElements();
this.functionalizeElements();
}
$('.infoItem').each(function(){
INFOITEM.initialize($(this));
});
</script>
<head>
<script type="text/javascript" src="systemJavascript/jquery-1.8.3.min.js"></script>
</head>
<body>
<div id="infoItem_123" class="infoItem">
<div class="menu">
<span class="menuOne">one</span>
<span class="menuTwo">two</span>
</div>
<div class="content">intro message</div>
<div class="contentOne">you clicked one</div>
<div class="contentTwo">you clicked two</div>
</div>
<div id="infoItem_456" class="infoItem">
<div class="menu">
<span class="menuOne">eins</span>
<span class="menuTwo">zwei</span>
</div>
<div class="content">Introtext</div>
<div class="contentOne">du hast auf eins geklickt</div>
<div class="contentTwo">du hast auf zwei geklickt</div>
</div>
</body>
</html>
<script type="text/javascript">
var INFOITEM = INFOITEM || {};
INFOITEM.initialize = function(infoItem) {
var elemMenuOne;
var elemMenuTwo;
var elemContent;
var elemContentOne;
var elemContentTwo;
var itemId;
this.defineVariables = function() {
elemMenuOne = infoItem.find('.menuOne');
elemMenuTwo = infoItem.find('.menuTwo');
elemContent = infoItem.find('.content');
elemContentOne = infoItem.find('.contentOne');
elemContentTwo = infoItem.find('.contentTwo');
itemId = infoItem.attr('id');
}
this.decorateElements = function() {
elemMenuOne.css('background-color', 'beige');
this.decorateAsLink(elemMenuOne);
elemMenuTwo.css('background-color', 'beige');
this.decorateAsLink(elemMenuTwo);
elemContentOne.hide();
elemContentTwo.hide();
}
this.functionalizeElements = function() {
that = this;
elemMenuOne.click(function(e) {
that.displayText($('#'+itemId), elemContentOne.html());
});
elemMenuTwo.click(function(e) {
that.displayText($('#'+itemId), elemContentTwo.html());
});
}
this.displayText = function(clickedInfoItem, text) {
clickedInfoItem.find('.content').html(text);
}
this.decorateAsLink = function(elem) {
elem.css({
'cursor' :'pointer',
'text-decoration' : 'underline',
'font-weight' : 'normal'
});
}
this.defineVariables();
this.decorateElements();
this.functionalizeElements();
}
$('.infoItem').each(function(){
INFOITEM.initialize($(this));
});
</script>
JQUERY CODE EXAMPLE: Base code to simply attach jQuery code to numberous like elements on page
added on Jan 8, 2013
Base code to simply attach jQuery code to numberous like elements on page
Use this code as a basis if you want to have numerous elements on a page which each act individually. The trick is to separate out the trigger elements from the relative elements.

PHP:
echo display();
function display() {
$r = '';
for ($x = 0; $x < 10; $x++) {
$r .= '<div class="quickReviewItem" data-item-id="' . $x . '"><span class="title">title</span><span class="message">nnn</span></div>';
}
return $r;
}
function display() {
$r = '';
for ($x = 0; $x < 10; $x++) {
$r .= '<div class="quickReviewItem" data-item-id="' . $x . '"><span class="title">title</span><span class="message">nnn</span></div>';
}
return $r;
}
calling jQuery from HTML:
$('.quickReviewItem').each(function(){
QUICKREVIEWITEM.initialize($(this));
});
QUICKREVIEWITEM.initialize($(this));
});
jQuery code:
var QUICKREVIEWITEM = QUICKREVIEWITEM || {};
QUICKREVIEWITEM.initialize = function(elemQuickReview) {
var elemTitle;
this.defineTriggerVariables = function() {
elemTitle = elemQuickReview.find('.title');
}
this.defineRelativeVariables = function(elem) {
elemMessage = elem.find('.message');
itemId = $.trim(elem.data('itemId')); //note: trim necessary to be able to compare string values
}
this.functionalizeElements = function() {
that = this;
elemTitle.click(function(e) {
that.defineRelativeVariables(elemTitle.parent());
e.preventDefault();
elemMessage.html(elemMessage.html() + 'new' + itemId);
});
}
this.decorateElements = function() {
elemTitle.css('color','brown');
elemTitle.css('cursor','pointer');
elemMessage.css('color','green');
elemMessage.html(elemMessage.html()+itemId);
}
this.defineTriggerVariables();
this.defineRelativeVariables(elemQuickReview);
this.decorateElements();
this.functionalizeElements();
}
QUICKREVIEWITEM.initialize = function(elemQuickReview) {
var elemTitle;
this.defineTriggerVariables = function() {
elemTitle = elemQuickReview.find('.title');
}
this.defineRelativeVariables = function(elem) {
elemMessage = elem.find('.message');
itemId = $.trim(elem.data('itemId')); //note: trim necessary to be able to compare string values
}
this.functionalizeElements = function() {
that = this;
elemTitle.click(function(e) {
that.defineRelativeVariables(elemTitle.parent());
e.preventDefault();
elemMessage.html(elemMessage.html() + 'new' + itemId);
});
}
this.decorateElements = function() {
elemTitle.css('color','brown');
elemTitle.css('cursor','pointer');
elemMessage.css('color','green');
elemMessage.html(elemMessage.html()+itemId);
}
this.defineTriggerVariables();
this.defineRelativeVariables(elemQuickReview);
this.decorateElements();
this.functionalizeElements();
}
UBUNTU BOOK NOTES: Ubuntu Unleased 2012 | 4.2
added on Jan 8, 2013
Ubuntu Unleased 2012
- chap1,has 12 variants, cloud, etc., warns against dual boot, you can try, wubi (ubuntu within windows);finished
- chap2,dmesg, sudo, apt-get update, installing drivers, hwclock, wireless;finished
- chap3,gnome and x, xorg.conf in /usr/share/X11, Unity (a fresh take on the GUI), workspaces nice and ctrl-alt-arrow;finished
- chap4,browsers and email clients, etc, then ubuntu one cloud storage;finished
- chap5,libreoffice etc;finished
- chap6,dvds, video, audio, etc;finished
- chap7,ldxe, lunbuntu, as of 4.10 gnome;finished
- chap8,games;finished
- chap9,apt-get to install and remove, very apt-get instructions, shows how to compile from source with apt-get;4.8
- chap10,command-line quickstart, ssh, ubuntu doesn't have a root account, would be a good read for directories in linux, how to add user but not groups, shutdown;finished
- chap11, more command-line, basics, fu, cp, find, grep, ln, whereis, tail, top, ps, using < for input, pipe for combining commands, xargs, tar;4.2
- chap12,managing users, learned: use the gui to create users, otherwise cannot login;3.2;be able to create users wihtout gui
- chap13,automating, at, cron, semicolon, regex in names, piping, writing shell script;4.8
- todo: write shell script, how to make scripts executable but didn't work (alias), basics of scripting, for, if, etc;4.3;learn basic scripting
- chap14, boot process, various infos on booting;finished
- chap15,
- chap16,
- chap17,
- chap18,
- chap19,
- chap20,
- chap21,
- chap22,
- chap23,
- chap24,
- chap25,
- chap26,
- chap27,
- chap28,
- chap29,
- chap30,
- chap31,
- chap32,
- chap33,
- chap34,
- chap35,
- chap36,
- chap37,
- chap38,
- chap39,
- chap40,
- chap41,
- chap42,
JQUERY CODE EXAMPLE: A simple JQuery/AJAX form with PHP processing page
added on Nov 16, 2012
A simple JQuery/AJAX form with PHP processing page
This is a simple HTML/JQuery/AJAX form that sends data via AJAX to a PHP page and displays the results.

HTML Page:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Testing - Test</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<script type="text/javascript" src="systemJavascript/jquery-1.8.2.min.js"></script>
<style type="text/css">
#result {
margin: 10px;
background: #eee;
padding: 10px;
height: 40px;
overflow: auto;
}
</style>
<script type="text/javascript">
$(function() {
SMARTFORM.initialize($('form#form1'));
SMARTFORM.initialize($('form#form2'));
});
var SMARTFORM = SMARTFORM || {};
SMARTFORM.initialize = function(form) {
var id = form.attr('id');
var elemsTextBoxes = form.find('input[type=text]');
var elemFirstField = form.find('input[type=text]').filter(':first');
var elemButton = form.find('#formButton');
var elemFieldFirstName = form.find('#firstName');
var elemFieldLastName = form.find('#lastName');
var elemResultArea = form.find('#resultArea');
elemsTextBoxes.on('focus', function() {
$(this).css('background-color', '#eee');
});
elemsTextBoxes.on('blur', function() {
$(this).css('background-color', '#fff');
});
elemFirstField.focus();
elemButton.click(function(e) {
e.preventDefault();
elemButton.blur();
elemFirstField.focus();
if(elemFieldFirstName.val() != '') {
$.post(
'testAjaxProcess2.php',
{
firstName: elemFieldFirstName.val(),
lastName: elemFieldLastName.val()
},
function( jsonString )
{
var data = $.parseJSON(jsonString);
elemResultArea.html(data['message']).hide().fadeIn('slow');
elemFieldFirstName.val('');
elemFieldLastName.val('');
elemButton.hide();
elemFieldFirstName.css('background-color', 'white');
});
} else {
elemFieldFirstName.css('background-color', 'red');
}
});
}
</script>
</head>
<body>
<form id="form1">
<h2>Form1</h2>
<div>First Name:<input type="text" id="firstName"/></div>
<div>Last Name:<input type="text" id="lastName"/></div>
<div><button id="formButton">Send</button></div>
<div id="resultArea">
</div>
</form>
<form id="form2">
<h2>Form2</h2>
<div>First Name:<input type="text" id="firstName"/></div>
<div>Last Name:<input type="text" id="lastName"/></div>
<div><button id="formButton">Send</button></div>
<div id="resultArea">
</div>
</form>
</body>
</html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Testing - Test</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<script type="text/javascript" src="systemJavascript/jquery-1.8.2.min.js"></script>
<style type="text/css">
#result {
margin: 10px;
background: #eee;
padding: 10px;
height: 40px;
overflow: auto;
}
</style>
<script type="text/javascript">
$(function() {
SMARTFORM.initialize($('form#form1'));
SMARTFORM.initialize($('form#form2'));
});
var SMARTFORM = SMARTFORM || {};
SMARTFORM.initialize = function(form) {
var id = form.attr('id');
var elemsTextBoxes = form.find('input[type=text]');
var elemFirstField = form.find('input[type=text]').filter(':first');
var elemButton = form.find('#formButton');
var elemFieldFirstName = form.find('#firstName');
var elemFieldLastName = form.find('#lastName');
var elemResultArea = form.find('#resultArea');
elemsTextBoxes.on('focus', function() {
$(this).css('background-color', '#eee');
});
elemsTextBoxes.on('blur', function() {
$(this).css('background-color', '#fff');
});
elemFirstField.focus();
elemButton.click(function(e) {
e.preventDefault();
elemButton.blur();
elemFirstField.focus();
if(elemFieldFirstName.val() != '') {
$.post(
'testAjaxProcess2.php',
{
firstName: elemFieldFirstName.val(),
lastName: elemFieldLastName.val()
},
function( jsonString )
{
var data = $.parseJSON(jsonString);
elemResultArea.html(data['message']).hide().fadeIn('slow');
elemFieldFirstName.val('');
elemFieldLastName.val('');
elemButton.hide();
elemFieldFirstName.css('background-color', 'white');
});
} else {
elemFieldFirstName.css('background-color', 'red');
}
});
}
</script>
</head>
<body>
<form id="form1">
<h2>Form1</h2>
<div>First Name:<input type="text" id="firstName"/></div>
<div>Last Name:<input type="text" id="lastName"/></div>
<div><button id="formButton">Send</button></div>
<div id="resultArea">
</div>
</form>
<form id="form2">
<h2>Form2</h2>
<div>First Name:<input type="text" id="firstName"/></div>
<div>Last Name:<input type="text" id="lastName"/></div>
<div><button id="formButton">Send</button></div>
<div id="resultArea">
</div>
</form>
</body>
</html>
Processing Page:
<?php
$data = array();
$firstName = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
$lastName = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
$data['message'] = 'Thank you, '. strtoupper($firstName) . ' ' . strtoupper($lastName) . ' was processed.';
echo json_encode($data);
$data = array();
$firstName = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
$lastName = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
$data['message'] = 'Thank you, '. strtoupper($firstName) . ' ' . strtoupper($lastName) . ' was processed.';
echo json_encode($data);
PHP CODE EXAMPLE: How to send multiple MySQL commands in one line from PHP
added on Jul 18, 2012
How to send multiple MySQL commands in one line from PHP
Although a semicolon-separated statement will work in e.g. phpmyadmin, you cannot just copy it to a string in PHP and execute it without splitting it and executing each command. This code shows you how.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
$sql = "SELECT @i:=0;
SELECT @i:=@i+1 AS `No.`,
CONCAT(c.FirstName, ' ', c.LastName) AS `Customer Name`,
CONCAT(e.FirstName, ' ', e.LastName) AS `Support Rep`
FROM customer AS c
JOIN employee AS e ON e.EmployeeId = c.SupportRepId";
$db = new mysqli('localhost', 'root', 'password', 'chinook');
$queries = preg_split("/;+(?=([^'|^\\\']*['|\\\'][^'|^\\\']*['|\\\'])*[^'|^\\\']*[^'|^\\\']$)/", $sql);
foreach ($queries as $query) {
if (strlen(trim($query)) > 0) {
$result = $db->query($query);
$numberOfColumns = $db->field_count;
if ($numberOfColumns > 1) {
echo '<table border="1">';
while ($row = $result->fetch_array()) {
echo '<tr>';
for ($x = 0; $x < $numberOfColumns; $x++) {
echo '<td>' . $row[$x] . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
}
?>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
$sql = "SELECT @i:=0;
SELECT @i:=@i+1 AS `No.`,
CONCAT(c.FirstName, ' ', c.LastName) AS `Customer Name`,
CONCAT(e.FirstName, ' ', e.LastName) AS `Support Rep`
FROM customer AS c
JOIN employee AS e ON e.EmployeeId = c.SupportRepId";
$db = new mysqli('localhost', 'root', 'password', 'chinook');
$queries = preg_split("/;+(?=([^'|^\\\']*['|\\\'][^'|^\\\']*['|\\\'])*[^'|^\\\']*[^'|^\\\']$)/", $sql);
foreach ($queries as $query) {
if (strlen(trim($query)) > 0) {
$result = $db->query($query);
$numberOfColumns = $db->field_count;
if ($numberOfColumns > 1) {
echo '<table border="1">';
while ($row = $result->fetch_array()) {
echo '<tr>';
for ($x = 0; $x < $numberOfColumns; $x++) {
echo '<td>' . $row[$x] . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
}
?>
</body>
</html>
SQL CODE EXAMPLE: How to find doubles in SQL
added on Jul 7, 2012
How to find doubles in SQL
This query finds all tracks ordered for two customers:
SELECT inv.BillingCity,cus.LastName,tra.Name
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
WHERE cus.LastName IN ('Schneider','Schröder')
ORDER BY inv.BillingCity,cus.LastName,tra.Name
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
WHERE cus.LastName IN ('Schneider','Schröder')
ORDER BY inv.BillingCity,cus.LastName,tra.Name

and this finds all tracks that a customer ordered multiple times:
SELECT cus.CustomerId,tra.Name,COUNT(cus.CustomerId) AS TheTotal
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
GROUP BY cus.CustomerId,tra.Name
HAVING TheTotal > 1
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
GROUP BY cus.CustomerId,tra.Name
HAVING TheTotal > 1
LINUX BOOK NOTES: Macintosh Terminal Pocket Guide | 4.8
added on Jul 7, 2012
Macintosh Terminal Pocket Guide
skimming: try all examples in ubuntu, should be about the same, would be useful to see where ubuntu differes as well, piping, lost of useful commands, background processes, etc, %%page64
- chap1,
- chap2,
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
- chap16,
- chap17,
- chap18,
- chap19,
- chap20,
CLOJURE FORAY: setup and use clojure in ubuntu






added on Jul 4, 2012
Setup and use clojure in ubuntu
- install
- get ubuntu running in virtualbox
- reading this guide
- sudo apt-get install clojure
- quote: Debian is the rock upon which Ubuntu is built.
- last thing it said was "ldconfig deferred processing now taking place", seems to have installed
- yes I get user=>
- did: (defn hello [name] (str "Hello, " name)), ok

- clojure basics
- define variable x to true

- another way to define z as true (constantly)

- define and execute a function:

- how to do a loop:

- how to call java from clojure:

- leiningen
- how to download and install Leiningen:
- download lein script
- create a new project:

- add a new dependency:

CLOJURE BOOK NOTES: Programming Clojure | 4.5
added on Jul 4, 2012
Programming Clojure
If you are not familiar with functional programming, Java, then is a very abtract book.
- chap1,why, functional programming is simple, best of java, lisp for the jvm, short programs, simpler, defrecord Person[first-name last-name], lisp reloaded, improves on lisp syntax, commas are whitespace, not a pure functional language like haskell, threadsafe, contrast with imperitive languages, where explicit statements alter program state, functional programming is more urgent, uses software transcational memory, clojure dynamic typing (many functional language statically typed), simplifies concurrent programming (thread-safe), embraces JVM, via git, REPL, *1 and *2, libraries, (doc str) for documentation, conventions;skimmed;4.6
- chap2, exploring clojure, nice abbreviations, macros, callings java, no for loop, cons for construct, functions return lists;skimmed;4.1
- chap3,sequences, maps, lazy and infinite sequences, regex use java.util.regex, peek/pop, somewhat like javascript object literals;skimmed;4.0
- chap4, functional programming, "how to be lazy", self-recursion, currying () and partial application, Trampolining Mutual Recursion, expose sequences instead of functions;skimmed;4.0
- chap5, state, software transactional memory, atoms and refs, unified update model, java callback apis, snake game; skimmed;2.3-state issues abstract
- chap6,protocols and databases, "spit and slurp i/o functions", gulp and expectorate, ok now they have files such as "src/examples/protocols.clj", interfaces, can create java interfaces in clojure, macros;skimmed;4.1-some code for reading databases
- question: where are the touch points between clojure and java?
- chap7, macros, if you can write it as a function, don't write a macro, defmacro, java interop;skimmed;3.7-said not to write macros
- chap8, multimethods, associate function with set of inputs (like polymorphism), defmulti, clojure's inspector library uses swing; skimmed;3.9-the polymorphism reference made sense
- chap9, java down and dirty, clojure compiles to bytecode, exception handling easy, creating java classes in clojure, logging;skimmed;3.5-didn't really show how it calls java
- chap10,building application, running tests, the REPL, has example with html output, deploying: lien run, example of deploying at heroku;skimmed;2.4-not really sure what the application was
- question: not really sure how clojure is used in relation to java, is it used in conjunction with java, instead of java, or does it use java?
WEB BOOK NOTES: Web Performance Daybook | 5.0
added on Jul 4, 2012
Web Performance Daybook
- chap1, talks about how webpagetest.org works, very technical;3.1;finished
- chap2,
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
- chap16,
- chap17,
- chap18,
- chap19,
- chap20,
- chap21,
- chap22,
- chap23,
- chap24,
- chap25,
- chap26,
- chap27,
- chap28,
- chap29,
- chap30,
- chap31,
- chap32,
- chap33,
JAVASCRIPT BOOK NOTES: The Linux Command Line | 5.0
added on Jul 4, 2012
The Linux Command Line
- chap1,launch the terminal, starts with "command not found", date, cal, df, free, exit;2.8;super basic;finished
- chap2,pwd, cd, ls, limit names to period, hyphen, underscore
- fc: goto home directory;cd
- fc: goto previous working directory;cd -
- fc: goto home directory of user;cd ~username
- chap3,file, etc. %%page50
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
- chap16,
- chap17,
- chap18,
- chap19,
- chap20,
- chap21,
- chap22,
- chap23,
- chap24,
- chap25,
- chap26,
- chap27,
- chap28,
- chap29,
- chap30,
- chap31,
- chap32,
- chap33,
- chap34,
JAVASCRIPT BOOK NOTES: Learning Node | 5.0
added on Jul 4, 2012
Learning Node
- preface, introductions and quotes;finished;3.1
- quote: True, you can use CoffeeScript with node.js, but JavaScript is the lingua franca of the technology.
- quote: If you explore the source code for Node, you'll find the source code for Google's V8.
- quote: One advantage to Node.js, then, is that you can develop Node applications for just one implementation of JavaScript.
- quote: Node is designed to be used for applications that are heavy on input/output, but light on computation.
- chap1, shows how to set up a development environment for Node in Windows 7 and Linux (Ubuntu).
- page6
- chap2,
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,l
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
- chap16,
GIT BOOK NOTES: Getting Good with Git (2010) | 5.0
added on Jun 25, 2012
Getting Good with Git (2010)
This is a very basic book which treats the user as if he hasn't used the command line before, i.e. first teaches "ls" for linux and "dir" for windows command line.
- chap1, introduction, it's a program, allows you to put marks in project;done;3.0
- quote: if you're grokking the concept of timeline markers for your code, you're understanding where Git fits in
- quote: with Git, your code repositories don't need to have a single home
- quote: almost everything you do with Git is done on your own machine
- checkout: whygitisbetterthanx.com (500 error)
- chap2, commands;done;done;1.0;very simplistic background to commandlines (ls and dir)
- quote: in GIT, 99% of everything you do on the command line is irreversible
- foray: get textmate working on ubuntu (mate)
- chap3, configuration, uses msysgit on windows, %%here:pg32
- recon: homebrew and macports for mac
- chap4, beyond the basics
- chap5, github
PHP CODE EXAMPLE: Base code to retrieve data from MySQL and display with PHP/mysql_connect
added on Jun 13, 2012
Base code to retrieve data from MySQL and display with PHP/mysql_connect
This is the simplest code that uses the mysql_connect commands to retreive data from a MySQL database and displays it in a nice table. (Get the Chinook database here.)

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
table thead tr td {
background-color: #ddd;
padding: 5px;
font-weight: bold;
}
table tbody tr td {
background-color: #eee;
padding: 5px;
color: navy;
}
div.sqlCommand {
font-family: courier;
}
</style>
</head>
<body>
<?php
$sql = 'SELECT LastName,FirstName FROM employee ORDER BY LastName';
$con = mysql_connect('localhost', 'root', 'thepass');
if (!$con) {
die('database error');
} else {
mysql_select_db('chinook', $con);
$result = mysql_query($sql);
$numberOfColumns = mysql_num_fields($result);
echo '<div class="sqlCommand">' . $sql . '</div>';
echo '<table>';
echo '<thead>';
echo '<tr>';
while ($property = mysql_fetch_field($result)) {
echo '<td>' . $property -> name . '</td>';
}
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
for ($x = 0; $x < $numberOfColumns; $x++) {
echo '<td>' . $row[$x] . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '<table>';
}
?>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
table thead tr td {
background-color: #ddd;
padding: 5px;
font-weight: bold;
}
table tbody tr td {
background-color: #eee;
padding: 5px;
color: navy;
}
div.sqlCommand {
font-family: courier;
}
</style>
</head>
<body>
<?php
$sql = 'SELECT LastName,FirstName FROM employee ORDER BY LastName';
$con = mysql_connect('localhost', 'root', 'thepass');
if (!$con) {
die('database error');
} else {
mysql_select_db('chinook', $con);
$result = mysql_query($sql);
$numberOfColumns = mysql_num_fields($result);
echo '<div class="sqlCommand">' . $sql . '</div>';
echo '<table>';
echo '<thead>';
echo '<tr>';
while ($property = mysql_fetch_field($result)) {
echo '<td>' . $property -> name . '</td>';
}
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
for ($x = 0; $x < $numberOfColumns; $x++) {
echo '<td>' . $row[$x] . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '<table>';
}
?>
</body>
</html>
JAVASCRIPT CODE EXAMPLE: JavaScript Singleton Refactored
added on Jun 11, 2012
JavaScript Singleton Refactored
This is a refactored version of my other JavaScript singleton. Basically the getInstance function was removed which also allowed me to remove the that = this, more succinct now:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var DatapodManager = (function() {
return {
message: 'singleton defined at ' + getMilliseconds(),
getMessage: function() {
return this.message;
},
id: '1234'
}
}());
function dowait() {
for(x=1; x<=10000000; x++) {
var y = 1000;
var z = 1000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: ' + getMilliseconds());
console.log(DatapodManager.getMessage());
dowait();
console.log('getting second singleton message at: ' + getMilliseconds());
console.log(DatapodManager.getMessage());
console.log('the static id is ' + DatapodManager.id);
};
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<script type="text/javascript">
var DatapodManager = (function() {
return {
message: 'singleton defined at ' + getMilliseconds(),
getMessage: function() {
return this.message;
},
id: '1234'
}
}());
function dowait() {
for(x=1; x<=10000000; x++) {
var y = 1000;
var z = 1000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: ' + getMilliseconds());
console.log(DatapodManager.getMessage());
dowait();
console.log('getting second singleton message at: ' + getMilliseconds());
console.log(DatapodManager.getMessage());
console.log('the static id is ' + DatapodManager.id);
};
</script>
</head>
<body>
</body>
</html>
JAVASCRIPT CODE EXAMPLE: Basic JavaScript Singleton
added on Jun 8, 2012
Basic JavaScript Singleton
I needed a singleton in JavaScript in order to make a DataManager which is called multiple times, but I just want it to load its data only the first time it is called, then give pieces of the data out view public methods, never loading the initial data again.

<!DOCTYPE html>
<html>
<head>
<title>test singleton</title>
<script type="text/javascript">
var DatapodManager = (function() {
var instantiated;
that = this;
//DEFINE INTERNAL VARIABLES HERE:
var message = '';
function init() {
//LOAD DATA ONCE HERE:
that.message = 'singleton message defined at: ' + getMilliseconds();
//ALLOW PUBLIC ACCESS TO SINGLETON DATA HERE:
return {
getMessage : function() {
return that.message;
},
id : '1234'
}
}
return {
getInstance : function() {
if(!instantiated) {
instantiated = init();
}
return instantiated;
}
}
})()
function dowait() {
for( x = 1; x <= 10000000; x++) {
var y = 1000;
var z = 2000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
dowait();
console.log('getting second singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
console.log('the static id is '+DatapodManager.getInstance().id);
};
</script>
</head>
<body></body>
</html>
<html>
<head>
<title>test singleton</title>
<script type="text/javascript">
var DatapodManager = (function() {
var instantiated;
that = this;
//DEFINE INTERNAL VARIABLES HERE:
var message = '';
function init() {
//LOAD DATA ONCE HERE:
that.message = 'singleton message defined at: ' + getMilliseconds();
//ALLOW PUBLIC ACCESS TO SINGLETON DATA HERE:
return {
getMessage : function() {
return that.message;
},
id : '1234'
}
}
return {
getInstance : function() {
if(!instantiated) {
instantiated = init();
}
return instantiated;
}
}
})()
function dowait() {
for( x = 1; x <= 10000000; x++) {
var y = 1000;
var z = 2000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
dowait();
console.log('getting second singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
console.log('the static id is '+DatapodManager.getInstance().id);
};
</script>
</head>
<body></body>
</html>
JAVASCRIPT CODE EXAMPLE: Example of using prototype property to add functionality to a class
added on Jun 7, 2012
Example of using prototype property to add functionality to a class
The following example shows how you can create an object (c1) from a class (Circle), then add a function to that class, which automatically is accessible by the object that was already created by the class.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var Circle = function(radius) {
this.radius = radius;
this.doubleRadius = function() {
return this.radius * 2;
}
}
var c1 = new Circle(4);
Circle.prototype.area = function() {
return Math.PI*this.radius*this.radius;
}
var c2 = new Circle(5);
console.log('--- first circle object, created before adding "area" method');
console.log(c1.radius);
console.log(c1.doubleRadius());
console.log(c1.area());
console.log('--- second circle object, created after adding "area" method');
console.log(c2.radius);
console.log(c2.doubleRadius());
console.log(c2.area());
console.log(c2.constructor.prototype); // Object { area=function() }
console.log(c2.__proto__); // Object { area=function() }
}
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var Circle = function(radius) {
this.radius = radius;
this.doubleRadius = function() {
return this.radius * 2;
}
}
var c1 = new Circle(4);
Circle.prototype.area = function() {
return Math.PI*this.radius*this.radius;
}
var c2 = new Circle(5);
console.log('--- first circle object, created before adding "area" method');
console.log(c1.radius);
console.log(c1.doubleRadius());
console.log(c1.area());
console.log('--- second circle object, created after adding "area" method');
console.log(c2.radius);
console.log(c2.doubleRadius());
console.log(c2.area());
console.log(c2.constructor.prototype); // Object { area=function() }
console.log(c2.__proto__); // Object { area=function() }
}
</script>
</head>
<body>
</body>
</html>
HTML5VIDEO FORAY: Make example of button jumping to middle of video and playing from there | 4.8
added on Jun 6, 2012
Make example of button jumping to middle of video and playing from there
- reading: http://blog.gingertech.net/2009/08/19/jumping-to-time-offsets-in-videos/
- bbc example: http://open.bbc.co.uk/rad/demos/html5/rdtv/episode2/index.html
- ok, no code examples worked there, going to current documentation: http://videojs.com/docs/api
- stripping down code to a simple example
HTML5VIDEO CODE EXAMPLE: Example of HTML5 video that plays in modern browsers
added on Jun 6, 2012
Example of HTML5 video that plays in modern browsers
To make this example, I used ffmpeg to encode a .mp4 video into .flv, .ogg, and .webm. I used the video.js which makes the VIDEO element compatible in all modern browsers. One thing I couldn't get to work is the Flash fallback for IE7 and IE8, but here is how it looks in the other browsers. Notice you have to have an .htaccess file to serve the right mime types.

I haven't yet been able to get the get IE6, IE7, and IE8 to successfully play the Flash video, the way I understand, if you provide the .flv file, VideoJS should take care of this itself.
.htaccess
AddType audio/ogg oga ogg
AddType video/ogg ogv
AddType video/webm webm
AddType video/x-flv flv
AddType video/ogg ogv
AddType video/webm webm
AddType video/x-flv flv
index.htm
<!DOCTYPE html>
<html>
<head>
<link href="videojs/video-js.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(init);
function init() {
setSmallSize();
$('button#buttonSmallSize').click(function() {
setSmallSize();
});
$('button#buttonLargeSize').click(function() {
setLargeSize();
});
}
function setSmallSize() {
$('video#my_video_1').css('width','512px');
$('video#my_video_1').css('height','288px');
$('div#videobox').css('width','512px');
$('div#videobox').css('height','322px');
$('button#buttonSmallSize').attr('disabled', true);
$('button#buttonLargeSize').attr('disabled', false);
}
function setLargeSize() {
$('video#my_video_1').css('width','768px');
$('video#my_video_1').css('height','432px');
$('div#videobox').css('width','768px');
$('div#videobox').css('height','468px');
$('button#buttonSmallSize').attr('disabled', false);
$('button#buttonLargeSize').attr('disabled', true);
}
</script>
<style type="text/css">
div#buttonRow {
margin: 0 0 12px 0;
}
.theButton {
float: left;
margin: 0 5px 0 0;
cursor: hand;
cursor: pointer;
}
.theMessage {
float: left;
margin: 0 5px 0 0;
font-family: arial;
color:#fff;
font-size: 14pt;
}
</style>
</head>
<body style="background-color: #888">
<div id="videobox" style="border-radius: 5px; width: 513px; padding: 10px; border: 1px solid #fff;background-image:url('images/chrome.jpg');;box-shadow: 10px 10px 5px #555">
<div id="buttonRow">
<button id="buttonSmallSize" class="theButton">Small Size</button>
<button id="buttonLargeSize" class="theButton">Large Size</button>
<div id="message" class="theMessage"></div>
<div style="clear:both"></div>
</div>
<video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" width="512" height="288" data-setup="{}">
Your browser is currently not supported.
<source src="videos/damconnect.mp4" type='video/mp4'>
<source src="videos/damconnect.webm" type='video/webm'>
<source src="videos/damconnect.ogg" type='video/ogg'>
<source src="videos/damconnect.flv" type='video/x-flv'>
</video>
</div>
</body>
</html>
<html>
<head>
<link href="videojs/video-js.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(init);
function init() {
setSmallSize();
$('button#buttonSmallSize').click(function() {
setSmallSize();
});
$('button#buttonLargeSize').click(function() {
setLargeSize();
});
}
function setSmallSize() {
$('video#my_video_1').css('width','512px');
$('video#my_video_1').css('height','288px');
$('div#videobox').css('width','512px');
$('div#videobox').css('height','322px');
$('button#buttonSmallSize').attr('disabled', true);
$('button#buttonLargeSize').attr('disabled', false);
}
function setLargeSize() {
$('video#my_video_1').css('width','768px');
$('video#my_video_1').css('height','432px');
$('div#videobox').css('width','768px');
$('div#videobox').css('height','468px');
$('button#buttonSmallSize').attr('disabled', false);
$('button#buttonLargeSize').attr('disabled', true);
}
</script>
<style type="text/css">
div#buttonRow {
margin: 0 0 12px 0;
}
.theButton {
float: left;
margin: 0 5px 0 0;
cursor: hand;
cursor: pointer;
}
.theMessage {
float: left;
margin: 0 5px 0 0;
font-family: arial;
color:#fff;
font-size: 14pt;
}
</style>
</head>
<body style="background-color: #888">
<div id="videobox" style="border-radius: 5px; width: 513px; padding: 10px; border: 1px solid #fff;background-image:url('images/chrome.jpg');;box-shadow: 10px 10px 5px #555">
<div id="buttonRow">
<button id="buttonSmallSize" class="theButton">Small Size</button>
<button id="buttonLargeSize" class="theButton">Large Size</button>
<div id="message" class="theMessage"></div>
<div style="clear:both"></div>
</div>
<video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" width="512" height="288" data-setup="{}">
Your browser is currently not supported.
<source src="videos/damconnect.mp4" type='video/mp4'>
<source src="videos/damconnect.webm" type='video/webm'>
<source src="videos/damconnect.ogg" type='video/ogg'>
<source src="videos/damconnect.flv" type='video/x-flv'>
</video>
</div>
</body>
</html>
MAGENTO BOOK NOTES: The Definitive Guide to Magento (2009) | 1.9
added on Jun 5, 2012
The Definitive Guide to Magento (2009)
This book is written for a designer (assumes you don't know php, html, css, says it will "hold your hand" as it goes through the code) and is a very rough overview, good to skim if you know nothing about Magento and just want to learn what it is and what are the moving parts are.
- chap1, introduction, opensource ecommerce platform, zend framework, two versions, began 2007, Varien, multiple websites with one admin, mulitple shipping addresses, etc;done;2.1
- chap2, installing, only linux, safe mode off, database, file permissions;4.2
- chap3, public interface walkthrough, most important: product page, upsell products, compare products, cms pages, checkout, billing;done;3.1
- chap4, admin walkthrough, basics, url rewrite management, ratings and tags, newsletter, reports, transaction emails;2.1;done
- chap5, products, many kinds of products: single, grouped, configurable, virtual, bundle, downloadable;2.1;done
- chap6, customers, checkout as guest, new customers, import, groups;1.8;done
- chap7, development, orders, creating invoice, but still from interface, not code, canceling, order on hold, deleting;2.8;done
- chap8, configuring, meta keywords, default home page, setting up transactional emails, setting up payment, sql script to remove all records;3.1;done
- chap9, customizing appearance, PHTML (from Zend) have basic structure plus the XML layouts from Magento, football metaphor: xml layouts = playbook, phtml = football players, skin=jersey colors, positive sides: global changes easy, MVC, potential problems: object-oriented steep, deep file structure, talks about themes, template path hints, shows xml layouts and phtml files, css file, blank theme,
- chap10, extensions, same: extensions, modules, plugins, i.e. extensions are packaged modules, extension key for pear files, how to build a module, hello world module, "Unfortunately, Magento's documentation is lacking.", then a random products module, overrides _toHtml(), then connects everything in config.xml, turning module into extension, make sure /var/pear exists, just filling out forms, you have to create a Magento Connect account, dependencies;2.1
- chap11, API, setting up magento for web services, using xml-rpc (pear client), using soap,
- chap12, tips and tricks, importing products with CSV, quickbooks invoices, how to truncate all tables (sql script);1.7
JQUERY CODE EXAMPLE: JavaScript module that displays quotes every couple seconds
added on Jun 4, 2012
JavaScript module that displays quotes every couple seconds
This is a Javascript module which displays quotes. It is self-contained so it won't conflict with other code (everyone under the namespace SMARTQUOTES). You can define the quotes and control the speed of the quotes through parameters, and you can control the layout of the quotes with CSS.

HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>smart quotes</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/smartquotes.js"></script>
<script type="text/javascript">
$(function() {
SMARTQUOTES.init();
SMARTQUOTES.quotes = new Array(
'It\'s tempting to augment prototypes of built-in constructors such as Object(), Array(), or Function(), but it can seriously hurt maintainability.',
'We come from XHTML backgrounds, so we will close all tags, use lowercase, and use quotation marks around attributes.',
'Checking to see if a value exists inside an array is always a bore in JavaScript.',
'JavaScript classes have the same effect on some people that garlic has on Dracula.',
'Mixins are not supported natively by CoffeeScript, for the good reason that they can be trivially implemented yourself.',
'Using a single var statement at the top of your functions is a useful pattern to adopt.',
'Using the Function() constructor is as bad as eval()',
'Any obstacle that I\'ve encountered during my development by placing JavaScript at the bottom of the page has been easily overcome and well worth the optimization gains.'
);
SMARTQUOTES.duration = 5000;
SMARTQUOTES.start();
});
</script>
<style type="text/css">
div#quoteWrapper {
border: 1px solid #999;
padding: 10px;
background: #eee;
color: navy;
width: 300px;
border-radius: 5px;
font-style: italic;
font-family: arial;
font-size: 12pt;
text-align: center;
}
</style>
</head>
<body>
<div id="quoteWrapper">
<div id="SMARTQUOTE"></div>
</div>
</body>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>smart quotes</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/smartquotes.js"></script>
<script type="text/javascript">
$(function() {
SMARTQUOTES.init();
SMARTQUOTES.quotes = new Array(
'It\'s tempting to augment prototypes of built-in constructors such as Object(), Array(), or Function(), but it can seriously hurt maintainability.',
'We come from XHTML backgrounds, so we will close all tags, use lowercase, and use quotation marks around attributes.',
'Checking to see if a value exists inside an array is always a bore in JavaScript.',
'JavaScript classes have the same effect on some people that garlic has on Dracula.',
'Mixins are not supported natively by CoffeeScript, for the good reason that they can be trivially implemented yourself.',
'Using a single var statement at the top of your functions is a useful pattern to adopt.',
'Using the Function() constructor is as bad as eval()',
'Any obstacle that I\'ve encountered during my development by placing JavaScript at the bottom of the page has been easily overcome and well worth the optimization gains.'
);
SMARTQUOTES.duration = 5000;
SMARTQUOTES.start();
});
</script>
<style type="text/css">
div#quoteWrapper {
border: 1px solid #999;
padding: 10px;
background: #eee;
color: navy;
width: 300px;
border-radius: 5px;
font-style: italic;
font-family: arial;
font-size: 12pt;
text-align: center;
}
</style>
</head>
<body>
<div id="quoteWrapper">
<div id="SMARTQUOTE"></div>
</div>
</body>
smartquotes.js
var SMARTQUOTES = SMARTQUOTES || {};
SMARTQUOTES.init = function() {
SMARTQUOTES.quoteIndex = 0;
SMARTQUOTES.duration = 3000;
SMARTQUOTES.quotes = [];
SMARTQUOTES.quotes[0] = 'test quote #1';
SMARTQUOTES.quotes[1] = 'this is the second quote';
SMARTQUOTES.quotes[2] = 'and now the third and last quote';
SMARTQUOTES.element = $('div#SMARTQUOTE').hide();
SMARTQUOTES.incrementQuote = function() {
SMARTQUOTES.quoteIndex++;
if(SMARTQUOTES.quoteIndex >= SMARTQUOTES.quotes.length) {
SMARTQUOTES.quoteIndex = 0;
}
}
SMARTQUOTES.displayQuote = function () {
var quote = SMARTQUOTES.quotes[SMARTQUOTES.quoteIndex];
SMARTQUOTES.element.fadeOut('slow', function() {
SMARTQUOTES.element.html(quote);
});
SMARTQUOTES.element.fadeIn();
SMARTQUOTES.incrementQuote();
SMARTQUOTES.startTimer();
}
SMARTQUOTES.startTimer = function () {
var t = setTimeout(SMARTQUOTES.displayQuote, SMARTQUOTES.duration);
}
SMARTQUOTES.start = function() {
SMARTQUOTES.quotes.sort(SMARTQUOTES.randomize);
SMARTQUOTES.displayQuote();
}
SMARTQUOTES.randomize = function(){
return (Math.round(Math.random())-0.5);
}
}
SMARTQUOTES.init = function() {
SMARTQUOTES.quoteIndex = 0;
SMARTQUOTES.duration = 3000;
SMARTQUOTES.quotes = [];
SMARTQUOTES.quotes[0] = 'test quote #1';
SMARTQUOTES.quotes[1] = 'this is the second quote';
SMARTQUOTES.quotes[2] = 'and now the third and last quote';
SMARTQUOTES.element = $('div#SMARTQUOTE').hide();
SMARTQUOTES.incrementQuote = function() {
SMARTQUOTES.quoteIndex++;
if(SMARTQUOTES.quoteIndex >= SMARTQUOTES.quotes.length) {
SMARTQUOTES.quoteIndex = 0;
}
}
SMARTQUOTES.displayQuote = function () {
var quote = SMARTQUOTES.quotes[SMARTQUOTES.quoteIndex];
SMARTQUOTES.element.fadeOut('slow', function() {
SMARTQUOTES.element.html(quote);
});
SMARTQUOTES.element.fadeIn();
SMARTQUOTES.incrementQuote();
SMARTQUOTES.startTimer();
}
SMARTQUOTES.startTimer = function () {
var t = setTimeout(SMARTQUOTES.displayQuote, SMARTQUOTES.duration);
}
SMARTQUOTES.start = function() {
SMARTQUOTES.quotes.sort(SMARTQUOTES.randomize);
SMARTQUOTES.displayQuote();
}
SMARTQUOTES.randomize = function(){
return (Math.round(Math.random())-0.5);
}
}
JQUERY BOOK NOTES: jQuery Recipes (2010) | 5.0
added on Jun 4, 2012
jQuery Recipes (2010)
- chap1, basics, selecting, each, prepend, preprendTo, clone();2.7;done
- recon: checkout author's page: http://bmharwani.com
- chap2, .join(), .each(words, function(index,value)), .get(), .map(), $.grep(), sorting numbers and letters (for numbers add a function a=b), splice(), combining arrays: mem1.concat(mem2),
- question: why get() if just the same as selection, p19
- codex: p25 grep/match
- codex: p41, display table from records, expand to ajax call
- chap3, events, bind(), you have clicked the $(this).text() button, trigger, unbind(), mousedown(), mouseup(), right/left button: event.button==1, position: event.screenX, event.screenY, image bright and blurred on mouseover, .focus(), .blur(), buttons (hover), toggleClass(),
- codex: p47, event.target, target is
- codex: p47, dblclick event
- codex: p54, mouse events
- codex: p61, how to make image bigger on maouse over (or flashcard)
- codex: p72, image based rollovers with csss
- codex: p80, text bubbles
- codex: p83, return to top links
- codex: p84, read more links
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10
HTML5VIDEO FORAY: use videojs to get three different formats (mpg, ogg, webm) playing in all browsers
added on May 30, 2012
Use videojs to get three different formats (mpg, ogg, webm) playing in all browsers
- getting at: http://videojs.com/
- built page:
<html>
<head>
<link href="http://vjs.zencdn.net/c/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/c/video.js"></script>
</head>
<body>
<video id="my_video_1" class="video-js vjs-default-skin" controls
preload="auto" width="640" height="264" poster="my_video_poster.png"
data-setup="{}">
<source src="videos/test.mp4" type='video/mp4'>
</video>
</body>
</html>
<head>
<link href="http://vjs.zencdn.net/c/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/c/video.js"></script>
</head>
<body>
<video id="my_video_1" class="video-js vjs-default-skin" controls
preload="auto" width="640" height="264" poster="my_video_poster.png"
data-setup="{}">
<source src="videos/test.mp4" type='video/mp4'>
</video>
</body>
</html>
- converting .mp4 to .ogg
- ffmpeg -i test.mp4 test.ogg
- http://ffmpeg.org/trac/ffmpeg/wiki/FilteringGuide
- or try this: ffmpeg -i test.mp4 -vf scale=512:-1 test.wmv
- browser compatibility: 70%
- chrome: plays well
- opera: plays well
- safari: plays well
- firefox:
- as file://.. if webm on top, plays well
- as localhost://...if webm on top,
plays without sound if ogg is on top
- IE9: plays but no CSS3 rounded corners, overlay bar is not correct
- NEXT: put in jquery and buttons to expand and retract size, also perhaps help screen with slide over effect
HTML5 BOOK NOTES: Dive into HTML5 (2010) | 5.0
added on May 29, 2012
Dive into HTML5 (2010)
- chap0,
- chap1,
- chap2,
- chap3,
- chap4,
- chap5, video,
- quote: There are tons of video codecs, the three most relevant are H.264, Theora, and VP8.
- quote: The AVI container format was invented by Microsoft in a simpler time, when the fact that computers could play video at all was considered pretty amazing.
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
- chapA,
- chapB,
HTML5 BOOK NOTES: HTML5 Canvas (May 2011) | 5.0
added on May 29, 2012
HTML5 Canvas (May 2011)
- chap1, intro, basic html5 page, hello world in canvas, getContext('2d'), puts on text and images, flash and silverlight are retained mode, canvas is immediate mode,
- recon: find libraries built on top of canvas
- codex: window.AddEventListener code as a boilerplate
- recon: http://diveintohtml5.org;5m
- foray: get codex with modernizr working;15m
- codex: page 12 hello world canvas with modernizer;4.9
- codex: page 12 Debugger;4.5
- quote: Once you get your head around it, the act of redrawing the screen every time there is an update makes the process of drawing to the canvas straightforward and simple.
- codex: How to dynamicaly resize the canvas in code
- codex: How to make a guess the letter game (game base); p17; 5.0
-
- chap2,
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
HTML5 BOOK NOTES: HTML5 Video (2010) | 3.0
added on May 29, 2012
HTML5 Video (2010)
- chap1, history, video table mentioned 2005, implemented 2007, IE joined march 2010, also: 1998: HTML+Time (but only for IE), 1997: SMIL (never supported by any browser accept as part of HTML+time), before video element, you could use embed or object, 2005: macromedia bought by adobe, 2007: mpeg supported in flash in particular H.264, goal: baseline codec, you have the ogg container which contains the theora video and vobis audio format, VP8 is on par in video quality with H.264, so it has a big chance of achieving baseline codec status, microsoft was positive to VP8, apple refrained from comment;done;4.8
- fc: which video containers typically contain which codecs?;WebM typically contains VP8 and Vorbis. Ogg typically contains Theora, Vorbis, Speex, or FLAC, and there are defined mappings for VP8 and Dirac, though not many such files exist. MP4 typically contains MP3, AAC, and H.264.
- fc: which video format did wikipedia choose?;Ogg Theora
- quote: although the video codec format should correctly be called "Ogg Theora/Vorbis", in common terminology you will only read "Ogg Theora".
- fc: what were the baseline HTML video/audio formats in 2007;Ogg Theora (video) and Ogg Vorbis (audio), however, apple supported H.264 in safari based on quality, h.264 supported by Nokia, Microsoft, ITU and ISO/IEC
- fc: what are the advantages of H.264 over Ogg Theora?; 1. better encoding quality, 2. youtube uses Flash with MP4 H.264/AAC support, 3. iphone/ipad/ipod hardward supports H.264
- fc: how is theora better than H.264?;less complex and therefore requiring less dedicated hardware support (good for mobile)
- fc: what is WebM?; an audio/video format to solve the stalemate of Ogg/Theora vs. MP4/H.264. WebM is a video container that contains VP8 video codec and Vorbis audio codec.
- fc: what is x264?; a free software library for encoding video streams into the H.264/MPEG-4 AVC format (steve jobs wrote to x264 developer asking opinion on VP8 codec)
- chap2, audio and video elements, examples all online here: http://html5videoguide.net, child elemetns: source, track + fallback content, safari/ie=mpeg, firefox/opera=webm/ogg, chrome=webm/ogg/mpeg, opera poster bug, put in width/height, audio support in browsers: ie=mp3, safari=wav/mp3, firefox/opera=wav/ogg, chrome=wav/ogg/mp3 (you need to provide ogg and mp3 in order to reach all browsers), codecs in source, shows a test of the video element, profiles in mp4 files, encoding ogg, encoding webm, mp3 and ogg vorbis, streaming with rtp and rtsp, rtsp (real video) will probably not be supported extensively, no real need for it, adaptive http streaming, %%2.4
- recon: look at javascript video libraries: mwEmbed1 (small), Video for Everybody (looks good), Sublime Video3 (small), or VideoJS (good), controls seem to be native,
- recon: xhtml5
- quote: The aim here is to continue using normal web servers without any software extensions and to push the complexity of streaming into the client software.
- quote: Key to the usability of progressive download is the ability to seek into not-yet downloaded sections by asking the web server to stop downloading and start providing those future data chunks.
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
PHP FORAY: on virtual win7 machine, setup: xampp, eclipse, svn, php, zend, debugging, xdebug | 4.8 






added on May 27, 2012
On virtual win7 machine, setup: xampp, eclipse, svn, php, zend, debugging, xdebug
- copy virtualbox machine (win7); finished
- started virtual box
- cloned general win7 to "windows7_zend", reinitialized mac addresses, full clone
- didn't ask me where it is putting it
- it's taking about 20 minutes and the machine seems a bit slow, thunderbird took a long time to open
- hmm, actually it was finished while it said "13 minutes to go", ok
- started virtual box, the rp password
- getting online
- installing xampp;finished
- went to http://www.apachefriends.org/en/xampp-windows.html
- downloading: 81 MB Installer, xampp-win32-1.7.7-VC9-installer
- executed
- got this error:

- installing in default c:\xampp
- installed apache adn mysql as service (not ftp)
- started copying at 2012-06-26 14:41:13
- clicked finish, checking ports...got this error

- allowed access on both
- it says finished
- says successful, start xamp control panel now, yes.
- it's running:

- testing
- typed: localhost in firefox, take over 30 seconds to find it
- restarting the machine, things are too slow
- powered off and on
- now faster
- localhost works
- giving mysql a password
- in cmd, went to c:\xampp\mysql\bin
- mysql -h localhost -u root
- set password for root@localhost = password('THEPASSWORD');
- then got error in phpmyadmin
- in config.inc.php changed auth_type to cookie:

- now you have to log in
- works but trying to set up a user didn't work, ok I found the answer, you have to delete the two "any" users OR set "edward" to localhost, otherwise the "any" users will overright his rights

- also, to hide the information_schema table from users, add this to the config.inc.php: $cfg['Servers'][$i]['hide_db'] = 'information_schema';
- restarted machine after windows updates and now apache server doesn't start, tried to uncheck as service, just checked itself again
- trying to restart again in services, worked
- virtual machine is very slow however
- click on "install guest additions", took awhile but finally reacted, installing
- it is a lot faster now, nice
- installing zend;finished
- reading: http://framework.zend.com/wiki/display/ZFDEV/Installing+Zend+Framework+on+Windows
- getting latest release here: http://framework.zend.com/download/latest
- chose: Zend Server Community Edition (CE)
- downloaded: Zend Server CE (PHP 5.3) (ZendServer-CE-php-5.3.9-5.6.0-SP1-Windows_x86.exe)
- installing
- typical (e.g. no dojo)
- says it is going to install apache:

- choose defaults: web server port: 8080 (had to change since 80 was occupied), zend port: 10081
- opened browser to: http://localhost:10081/ZendServer/Login#1340801331395
- accepted license, entered password (tp...)
- http://localhost:10081/ZendServer comes up with admin console
- localhost still goes to xampp
- localhost:8080 goes to a "Zend Server Test Page"
- turned on .htaccess file since "Without this redirection, the application does not work."
- ok, in both the xampp and zend apaches, the line "LoadModule rewrite_module modules/mod_rewrite.so" was uncommented
- also repalced all "AllowOverride None" with "AllowOverride All" in conf file
- restarted apache zend
- localhost:8080 and localhost:10081 work again
- setting up zend website;finished
- typed "zf show version", got "zend monitor ui is disabled in cli/cgi run"
- went into http://localhost:10081/ZendServer/ but don't see where to enable zend monitor ui:

- ok, but it says version 1.11.11
- typed "zf create project APACHE_HOME/htdocs/edwardtest"
- said it couldn't find directory
- typed "zf create project C:\Program Files\Zend\Apache2\htdocs\edwardtest" worked.
- said web project was created but not phpunit
- however, no directory has been created at zf create project C:\Program Files\Zend\Apache2\htdocs\edwardt
- ok, it says it created it at "C:\Program" hence space is probably issue
- typed: zf create project "C:\Program Files\Zend\Apache2\htdocs\edwardtest"
- opened cmd as administrator, it worked;solution
- interesting, as administrator it doesn't give zend monitor ui error;$learned=when zend/win7 command line always as administrator
- looking through new application
- can access it here: http://localhost:8080/edwardtest/public/

- configs
- application.ini, nice: staging, etc.
- controllers
- errorcontroller: bootstrap...
- models
- empty
-
(no image found with Id-Code = "win7zend")
[] check mysql
DEVELOPER FORAY: get a system going for having a library of ubuntu and win7 machines in virtualbox | 4.5 





added on May 27, 2012
Get a system going for having a library of ubuntu and win7 machines in virtualbox
- goal: to make it easy to save states of virtual machines, move them, etc.
- opening and changing current ubuntu
- made a file and saved with window open
- closed machine
- I can't change the machine while saved (like vmware)
- found the virtual disk image at: C:\Users\Edward\VirtualBox VMs\Ubuntu\Ubuntu.vdi
- copying it over to external drive
- creating new machine
- when adding the virtual drive on F:, it says that it can't read it, but then I continued and it worked
- renaming to Ubuntu_base001.vdi to see if I can still load it
- (you can change the file, file, global...)
- discarded saved state from first machine
- two machines have the same drive, testing if I can change one and it changes the other
- first machine made file, turned off
- when I tried to take a screenshot, it said "failed to create":

- getting the update to 4.1.16
- it installed a number of devices (usb etc.)
- said I had an old version of virtualbox extension pack and installed, quick
- started machine 1 again
- got error again:
- Failed to create a snapshot of the virtual machine Ubuntu.
- starting as admin
- tried renaming the hard drive and using it on the same machine but you cannot because they have guids, even after I deleted the first:

- creating a new machine and trying to use the renamed drive from another machine, doesn't work:

- trying to use the drive on another machine, no, doesn't work:

- zipping whole machine and moving it
- renamed drive back to original and started ubuntu1, worked
- zipping whole vm directory (C:\Users\Edward\VirtualBox VMs\Ubuntu), interseting: zipped all files including 3GB down to 1GB zip
- copied, extracting...
- interesting, even though I deleted the disk, just because it was open on the machine, it says it cannot add one with the same UUID

- ok, went into the virtual media manager and deleted it
- did a copy virtual disk, created it
- started copied machine and it says it doesn't have usb 2.0 controller
- tried to install extension pack but got error "exptected 4.0 got 4.1" (ok, just downloaded wrong one, installing was easy, from website)
- nice, it copied fine
- so: ubuntu machines are able to be created and copied
- took a snapshot on the second machine and it worked
- installing guest additions (ran autorun.sh), installed, made two shared folders, one a plain name, and one at /home/edward/test222, rebooting,
- creating instructions for creating new Ubuntu machines:
- trying to get two ubuntu machines running one
- right click, clone, then:

- full clone
- takes about 3 minutes to clone

- how to create a new ubuntu machine
- unzip file on external drive
- copy the machines directory to hard drive
- start machine
- use this machine to clone other machines and rename
- NEXT: Create and store win7 machine, done
- NEXT: Create and store winxp machine
ZEND BOOK NOTES: Beginning Zend Framework (2009) | 4.9
added on May 27, 2012
Beginning Zend Framework (2009)
- chap1,goals: setup apache, mysql, php 5.2.4 or later, and zend 1.8, does windows and mac installs, mamp, getting php and apache to talk, turn on .htaccess, Zend_Tool, creates controllers, actions, etc. , .htaccess lowers performance, php unit in test;4.9
- chap2, the application, creates an mp3 application, just talks about pages, mysql;3.1
- chap3, writing controllers, extend Zend_Controller_Action, transforming urls to controllers/actions, hmm, not a lot of code,
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
JAVASCRIPT BOOK NOTES: Backbone.js Applications (April 2012) | 5.0
added on May 27, 2012
Backbone.js Applications (April 2012)
- chap1, deep talk about mvc, history of it, var buildPhotoView = function( photoModel, photoController ){ , backbone, spine, then mvp,
- quote: The benefit of MVP over MVC is that it increases testability and provides cleaner separation between view and model, however, MVP lacks data binding support.
- quote: Use MVP if you have complex views with a great deal of user interaction since solving this in MVC may mean spreading this logic over many controllers.
- quote: since in MVP presenters communicate with views through interfaces, developers can create presenters before designers have created the views
- quote: there's quite a difference between opting for MVP for a JavaScript project over one for say, ASP.NET
- quote: JavaScript developers don't view MVC and MVP as being mutually exclusive
- quote: some developers feel that Backbone.js better fits the description of MVP than MVC
- quote: the V in MVC and the P in MVP can both be accomplished by Backbone.View
- fc: name three javascript mvc frameworks; Ember.js, JavaScriptMVC, and of course Backbone.js
- quote: In Backbone, controller logic is shared between Backbone.View and Backbone.Router.
- fc: what is the difference between mvc and mvp?;
- quote: Backbone is maintained by a number of contributors, most notably: Jeremy Ashkenas, creator of CoffeeScript, Docco and Underscore.js.
- chap2, the basics, Model.get(), Listening for changes to your model, talks about el, Collections are sets of Models, routers, Backbone.history, namespacing, scaffolding, documentcloud uses only one router;4.6
- fc: what are the top contenders for javascript templating?;Mustache, jQuery-tmpl (also look at handlebar.js as alternative to mustache)
- quote: The key to building large applications is not to build large applications in the first place.
- chap3, REST applications, with node.js, express, mongoose, mongodb, and jade, technical details, then: backbone with ruby, sinatra, mongodb, haml, how to install all;4.8;good intro to new technologies
- fc: what is jade; template engine influenced by haml, supports express
- fc: what is sinatra; a simpler ruby on rails, ties specific urls to blocks of ruby code, uses splats, redirection, halting, passing,
- quote: Haml looks more like CSS than it does traditional markup.
- quote: I personally found developing APIs with Sinatra a relatively painless experience.
- chap4, modular javascript, requirejs and AMD,
- foray: get requirejs running;4.8
- chap5,
- chap6,
- chap7,
JQUERY CODE EXAMPLE: Simple JavaScript to show time counting with setTimeout()
added on May 24, 2012
Simple JavaScript to show time counting with setTimeout()
Simplest code to loop continuously calling a function which shows the time.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>show time with timeout</title>
<script type="text/javascript">
window.onload = function() {
displayQuote();
startTimer();
};
function displayQuote() {
var quoteElem = document.getElementById('quote');
var dt = new Date();
quoteElem += quoteElem.innerHTML = dt.toTimeString();
startTimer();
}
function startTimer() {
var t = setTimeout(displayQuote, 1000);
}
</script>
</head>
<body>
--<div id="quote"></div>--
</body>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>show time with timeout</title>
<script type="text/javascript">
window.onload = function() {
displayQuote();
startTimer();
};
function displayQuote() {
var quoteElem = document.getElementById('quote');
var dt = new Date();
quoteElem += quoteElem.innerHTML = dt.toTimeString();
startTimer();
}
function startTimer() {
var t = setTimeout(displayQuote, 1000);
}
</script>
</head>
<body>
--<div id="quote"></div>--
</body>
HTML5 BOOK NOTES: HTML5 Developer's Cookbook (Dec 2011) | 5.0
added on May 24, 2012
HTML5 Developer's Cookbook (Dec 2011)
- intro, WHATWG worked on web forms 2.0 and web applications 1.0 which merged to form html5, in 2006 W3C left xhtml and picked up on html5 and called it "html 5", whatwg is much faster than w3c, in 2009 w3c stopped xthml, now html5 is primarily developed by whatwg and w3c reviews it, html5 backward compatible, html5 tells browsers to handle errors, very few recipes use third-party libraries, but they use standard javascript
- fc: what is html5; umbrella term for: html, css, javascript apis and events
- fc: name 12 html5 features: semantics, forms, canvas, drag/drop, local storage, page-to-page messaging, desktop notifications, video/audio, web sockets, geolocation (not technically part html5), history, microdata
- fc: is css3 part of html5?; no, it's just new and cool like html5
- checkout: html5doctor.com
- chap1, 20 new elements, doctype, charset, , js and css links, google analyzed class names to get new elements, header, does not have to be at top, multiple per page, hgroup, article and section, aside, footer, example as news page,
- quote: We come from XHTML backgrounds, so we will close all tags, use lowercase, and use quotation marks around attributes.
- quote: the HTML5 specification suggests that author information is more suited to the footer element
- question: what about backwards compabitility?
- quote: There is a big accessibility win when using the nav element.
- quote: A section can contain article elements, and article elements can have their content split into sections.
- quote: A common mistake in early HTML5 uptake is using a section to wrap entire sites.A common mistake in early HTML5 uptake is using a section to wrap entire sites.
- quote: The HTML5 specification says the footer element can include links to related documents.
- recon: tryout HTML5 outliner extension plugin for chrome: http://code.google.com/p/h5o/;3.7;15m
- codex: page 23, example article using new html5 elements;4.5;20m
- chap2,grouping, figure/figcaption, time element, address, details, mark (highlight), s element (inaccurate or irrelevant), ol has been redefined (interesting), now has reversed, the dl element, small for e.g. copyright info, i means "alternative voice or mood", now only abbr (not acronym), hr is now a "break after a paragraph", applet is gone, in HTML5 you can wrap a number of elements in the anchor element, jquery calendar, polifils, shims and libraries,
- quote: The i element was, in HTML 4, for styling text in italics. Now, though, it represents text that is in an alternative voice or mood.
- fc: what are the 5 HTML5 microdata attributes; itemid, itemprop, itemref, itemscope, and itemtype
- quote: You can actually combine Microdata with Microformats, and although Microdata is the emerging standard, Microformats is currently more popular.
- fc: what does WAI-ARIA stand for; Web Accessibility Initiatives Accessible Rich Internet Applications
- codex: modernizer, p62
- recon: check out these sites: http://findmebyIP.com, http://caniuse.com, http://html5test.com, http://html5readiness.com
- chap3, CSS Media Queries,
- recon: http://selectivizr.com), an easy-to-use JavaScript utility that makes Internet Explorer understand the new CSS selectors.; 3.2
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
JQUERY CODE EXAMPLE: Minimal start page for HTML5/JQuery
added on May 24, 2012
Minimal start page for HTML5/JQuery
This zip file has an html page, local jquery, a main.js, plus two css files, a good starter template for HTML5 with JQuery.

main.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 minimal start page</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link type="text/css" rel="stylesheet" href="css/reset.css" />
<link type="text/css" rel="stylesheet" href="css/main.css" />
</head>
<body>
<p>text has no borders from reset.css</p>
<p>is blue from main.css</p>
<p>is bold from jquery</p>
</body>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 minimal start page</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link type="text/css" rel="stylesheet" href="css/reset.css" />
<link type="text/css" rel="stylesheet" href="css/main.css" />
</head>
<body>
<p>text has no borders from reset.css</p>
<p>is blue from main.css</p>
<p>is bold from jquery</p>
</body>
reset.css
* {
margin: 0;
padding: 0;
}
img, fieldset {
border: 0;
}
margin: 0;
padding: 0;
}
img, fieldset {
border: 0;
}
main.css
p {
color: blue;
}
color: blue;
}
main.js
$(init);
function init() {
$('p').css('font-weight', 'bold');
}
function init() {
$('p').css('font-weight', 'bold');
}
JAVASCRIPT BOOK NOTES: Little Book on CoffeeScript (Jan 2012) | 4.8
added on May 23, 2012
Little Book on CoffeeScript (Jan 2012)
- preface, you can use it in node.js;3.2
- quote: CoffeeScript tends to run as fast or faster than handwritten JavaScript.
- quote: Now is definitely the time to jump on the CoffeeScript train.
- raid: coffeescript.org
- recon: j2coffee
- codex: browser-based coffeescript tag
- chap1, syntax, whitespace, function and var aren't permitted, function becomes arrow, inspect, new array features, range;4.4
- recon: coffeescript on windows, if not, on ubuntu vms
- quote: checking to see if a value exists inside an array is always a bore in JavaScript
- chap2, class keyword, fat arrows, has "extends", nice, mixins, ;4.9
- quote: JavaScript classes have the same effect on some people that garlic has on Dracula
- quote: it turns out that classes are just as useful in JavaScript as they are in other languages and CoffeeScript provides a great abstraction
- quote: Mixins are not supported natively by CoffeeScript, for the good reason that they can be trivially implemented yourself.
- quote: Mixins are pretty neat, but they're not very object oriented.
- chap3,
- chap4,
- chap5,
- chap6,
JAVASCRIPT CODE EXAMPLE: How to use prototype to add a method to a function/object
added on May 22, 2012
How to use prototype to add a method to a function/object
This code shows how JavaScript differs from C#/Java/etc. in that you can define a function (like a class), then instantiate an "object" of that function, then with the prototype keyword add a method to the function which is immediately present in the object which you just instantiated.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(init);
function init() {
function Book(title, numberOfPages) {
this.title = title;
this.numberOfPages = numberOfPages;
}
book = new Book('JS Book', 234);
console.log(book.title);
Book.prototype.display = function() {
return this.title + '('+this.numberOfPages+' pages)';
};
console.log(book.display());
}
</script>
<title>test singleton</title>
</head>
<body>
<p>test</p>
</body>
</html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(init);
function init() {
function Book(title, numberOfPages) {
this.title = title;
this.numberOfPages = numberOfPages;
}
book = new Book('JS Book', 234);
console.log(book.title);
Book.prototype.display = function() {
return this.title + '('+this.numberOfPages+' pages)';
};
console.log(book.display());
}
</script>
<title>test singleton</title>
</head>
<body>
<p>test</p>
</body>
</html>
JAVASCRIPT BOOK NOTES: JavaScript Patterns (2010) | 5.0
added on May 22, 2012
JavaScript Patterns (2010)
- chap1,patterns, oop, no classes, prototypes, one way to reuse code, ECMAScript 5 (dec 2009), console;2.1
- foray: jslint
- quote: JSLint will hurt your feelings, but only in the beginning.
- chap2, essentials, lots of tips that experienced javascript developers know, the problem with globals, don't forget var, access to global, single var pattern, hoisting (multiple vars), avoid eval(), not on parseInt() with radix number, white space, indentation, jslint;4.4
- quote: Using a single var statement at the top of your functions is a useful pattern to adopt.
- quote: it's also a good practice initialize the variable with an initial value at the time you declare it
- quote: Technically, you can also use for-in to loop over arrays, but it's not recommended.
- quote: So it's preferable to use normal for loops with arrays and for-in loops for objects.
- quote: It's tempting to augment prototypes of built-in constructors such as Object(), Array(), or Function(), but it can seriously hurt maintainability.
- recon: http://code.google.com/p/jsdoc-toolkit
- fc: two documentation tools for javascript: jsdoc, yuidoc
- chap3,literals and constructors, two ways to create same object, the new keyword (no reason to use it), shows the that pattern to enforce new, another solution: self-involing constructor, two ways to make arrays;4.7
- quote: when you forget new, this inside the constructor will point to the global object, JSON, regex, literal and primitives,
- quote: ECMAScript 5 defines a new method Array.isArray()
- fc: name javascript's primitive types;there are 5: number, string, boolean, null, undefined (the first three have primitive wrapper objects)
- chap4, functions, named and anonymous functions, functional hoisting, callbacks, return a function (closure), self-defining function (lazy function definition), parameters to immediate functions, configuration objects, curry (talks about apply), or without an array, currying (partial list of arguments),
- quote: Using the Function() constructor is as bad as eval()
- codex: do callback example, page 63;4.8
- quote: an immediate function allows you wrap an amount of work you want to do without leaving any global variables behind
- chap5, object creation patterns, shows how to avoid globals, namespaces, upfront declaration of variables in functions, private/public methods, priveleged prototype method, talks about method pattern and how it is not that recommended.
- codex: page 107, do wrapped function, and on next page, the constructor;4.8
- chap6, code reuse, ;4.8;this chapter explains the classical/modern approach to programming javascript with classes and not,
- quote: We call "modern" any JavaScript patterns that do not require you to think about classes.
- quote: Saying 'constructor function' instead of 'class' is longer, but it's accurate and not ambiguous.
- quote: It's important to remember that the prototype property should point to an object, not a function
- todo: use this chapter for talking about approaches to javascript in terms of objects, video
- chap7,
- chap8,
JAVASCRIPT BOOK NOTES: Oreilly Learning JavaScript Design Patterns (May 2012) | 5.0
added on May 19, 2012
Oreilly Learning JavaScript Design Patterns (May 2012)
You can skip to chapter 9 where the patterns start.
- chap1, intro, short;0.1;done
- chap2, what is pattern; 0.1;done
- chap3, more on what it is; 0.1;done
- chap4, structure; 0.1;done
- chap5, how to write them; 0.1;done
- chap6, antipatterns, eval(); 0.1;done
- chap7, categories, short;0.1;done
- chap8, categorization, emulating classes, lists all classic patterns;3.2
- chap9, many design patterns: creator, constructor, constructor with prototype, singleton, module, talks about how implemented by dojo, extjs, yui, jquery, observer, more patterns, html templates, comparisons: mediator vs. observer, mediate vs. facade, prototype pattern, command pattern, facade, factory, mixins, decorator, interfaces, decorators in jquery;5.0
- chap10, flyweight, used when code is using a lot of memory, flyweight and data layer, factory;4.1
- chap11, mvc for javascript, models, views, controllers, how implemented in spine.js and backbone.js, also MVP (allows you to mock views in unit tests), MVP uses a passive view (a very dumb view), mvp or mvc?, also talks about MVVM in KnockoutJS, Kendo MVVM and Knockback.js, compares them all, Backbone.js Vs. KnockoutJS, namespacing patterns ; 5.0
- chap12, patterns in jquery, module, lazy initialization, composite, adapter, facade, obverver with trigger/unbind, etc., interator, strategy (family of algorithms), proxy, builder, prototype (templates);4.5
- chap13, decoupling your apps, AMD plugins (Asynchronous Module Definition), from dojo, AMD is a format for writing modular javascript, define(), require(), loading amd modules using requirejs, commonJS (group that is standardizing javascript APIs);2.9
- chap14, jquery plugin design patterns, namespacing, pub/sub, jQuery UI Widget Factory Bridge, a lot more about plugins;3.1
CSS3 CODE EXAMPLE: How to use :nth-child(3n+1)
added on May 19, 2012
How to use :nth-child(3n+1)
If you change the 3 to 4 it is every fourth line, if you change the 1 to 2 it starts at "line number 2" instead of "line number 1".

<html>
<head>
<style type="text/css">
p {
margin: 0;
}
div#content > p:nth-child(3n+1) {
color:red;
}
div#content > *:last-child {
border-bottom: 1px solid red;
background-color: yellow;
}
div#content > div.comment:first-of-type {
color: blue;
font-weight: bold;
}
p:enabled {
}
</style>
</head>
<body>
<div id="content">
<?php
for($x=1; $x <=15; $x++) {
echo '<p>this is line number '.$x.'</p>';
echo '<div class="comment">this is a comment</div>';
}
?>
</div>
</body>
</html>
<head>
<style type="text/css">
p {
margin: 0;
}
div#content > p:nth-child(3n+1) {
color:red;
}
div#content > *:last-child {
border-bottom: 1px solid red;
background-color: yellow;
}
div#content > div.comment:first-of-type {
color: blue;
font-weight: bold;
}
p:enabled {
}
</style>
</head>
<body>
<div id="content">
<?php
for($x=1; $x <=15; $x++) {
echo '<p>this is line number '.$x.'</p>';
echo '<div class="comment">this is a comment</div>';
}
?>
</div>
</body>
</html>
JQUERY CODE EXAMPLE: How to allow user to press keys to affect objects on screen
added on May 18, 2012
How to allow user to press keys to affect objects on screen
The user can press the 1, 2, and 3 keys to make the divs slid up and back into view.

<!DOCTYPE html>
<html>
<head>
<title>alt key</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(document).keydown(function(event) {
switch(event.which) {
case 49:
$('div:first').slideToggle('slow');
return false;
break;
case 50:
$('div:last').slideToggle('slow');
return false;
break;
case 51:
$('div').slideToggle('slow');
return false;
break;
}
});
});
</script>
<style type="text/css">
div {
border: 1px solid #DDDDDD;
height: 200px;
width: 200px;
padding: 10px;
margin: 5px;
float: left;
}
</style>
</head>
<body>
<div>
press 1 to toggle
</div>
<div>
press 2 to toggle
</div>
<p style="clear: both">
</p>
<p>
press 3 to toggle both
</p>
</body>
</html>
<html>
<head>
<title>alt key</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(document).keydown(function(event) {
switch(event.which) {
case 49:
$('div:first').slideToggle('slow');
return false;
break;
case 50:
$('div:last').slideToggle('slow');
return false;
break;
case 51:
$('div').slideToggle('slow');
return false;
break;
}
});
});
</script>
<style type="text/css">
div {
border: 1px solid #DDDDDD;
height: 200px;
width: 200px;
padding: 10px;
margin: 5px;
float: left;
}
</style>
</head>
<body>
<div>
press 1 to toggle
</div>
<div>
press 2 to toggle
</div>
<p style="clear: both">
</p>
<p>
press 3 to toggle both
</p>
</body>
</html>
JQUERY CODE EXAMPLE: How to determine how long JQuery various selectors take to process
added on May 18, 2012
How to determine how long JQuery various selectors take to process
This shows a simple way to compare how long various selectors take to process, we see here that (in Firefox 11.0), it takes :first almost ten times as long as .first() to process.

<!DOCTYPE html>
<html>
<head>
<title>lasksdjf</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var i, time = +new Date;
for( i = 0; i < 10000; i++) {
$('div:first');
}
console.log((+new Date) - time);
time = +new Date;
for( i = 0; i < 10000; i++) {
$('div').first();
}
console.log((+new Date) - time);
});
</script>
</head>
<body>
<div>
111
</div>
<div>
222
</div>
<div>
333
</div>
</body>
</html>
<html>
<head>
<title>lasksdjf</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var i, time = +new Date;
for( i = 0; i < 10000; i++) {
$('div:first');
}
console.log((+new Date) - time);
time = +new Date;
for( i = 0; i < 10000; i++) {
$('div').first();
}
console.log((+new Date) - time);
});
</script>
</head>
<body>
<div>
111
</div>
<div>
222
</div>
<div>
333
</div>
</body>
</html>
JQUERY CODE EXAMPLE: Basic template code for JQuery using an init() function
added on May 18, 2012
Basic template code for JQuery using an init() function
There are many ways to get JQuery loaded and started in an HTML page, this example uses an init function.

<!DOCTYPE html>
<html>
<head>
<title>jqstart2</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(init);
function init() {
$('p#message').css('color','yellow');
$('p#message').css('background-color','#ccc');
}
</script>
</head>
<body>
<p id="message">this is the message</p>
</body>
</html>
<html>
<head>
<title>jqstart2</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(init);
function init() {
$('p#message').css('color','yellow');
$('p#message').css('background-color','#ccc');
}
</script>
</head>
<body>
<p id="message">this is the message</p>
</body>
</html>
JAVASCRIPT CODE EXAMPLE: Basic template code for HTML/JavaScript using the onload attribute in BODY
added on May 18, 2012
Basic template code for HTML/JavaScript using the onload attribute in BODY
There are many ways to get JavaScript working in an HTML page, this example calls an init function from the body element.

<!DOCTYPE html>
<html>
<head>
<title>javascript start 2</title>
<script type="text/javascript">
function init() {
var elemMessage = document.getElementById('message');
elemMessage.style.color = 'navy';
elemMessage.style.backgroundColor = 'orange';
}
</script>
</head>
<body onload="init();">
<p id="message">this was changed in init</p>
</body>
</html>
<html>
<head>
<title>javascript start 2</title>
<script type="text/javascript">
function init() {
var elemMessage = document.getElementById('message');
elemMessage.style.color = 'navy';
elemMessage.style.backgroundColor = 'orange';
}
</script>
</head>
<body onload="init();">
<p id="message">this was changed in init</p>
</body>
</html>
JAVASCRIPT CODE EXAMPLE: Basic template code for HTML/JavaScript using window.onload
added on May 18, 2012
Basic template code for HTML/JavaScript using window.onload
This code shows how to assign an element to a variable and change its color.

<!DOCTYPE html>
<html>
<head>
<title>lasksdjf</title>
<script type="text/javascript">
window.onload = function() {
var title = document.getElementById('title');
title.style.color = 'blue';
};
</script>
</head>
<body>
<div id="title">this is the title</div>
</body>
</html>
<html>
<head>
<title>lasksdjf</title>
<script type="text/javascript">
window.onload = function() {
var title = document.getElementById('title');
title.style.color = 'blue';
};
</script>
</head>
<body>
<div id="title">this is the title</div>
</body>
</html>
JQUERY CODE EXAMPLE: Basic template code to load JQuery remotely with setOnLoadCallback
<!DOCTYPE html>
<html>
<head>
<title>jquery load</title>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('jquery', '1.7.1');
google.setOnLoadCallback(function() {
$('p#message').addClass('highlight');
});
</script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p id="message">This is the message</p>
</body>
</html>
added on May 18, 2012
Basic template code to load JQuery remotely with setOnLoadCallback
The latest version at the time was 1.7.2 but this couldn't load it, but could load 1.7.1.

<!DOCTYPE html>
<html>
<head>
<title>jquery load</title>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('jquery', '1.7.1');
google.setOnLoadCallback(function() {
$('p#message').addClass('highlight');
});
</script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p id="message">This is the message</p>
</body>
</html>
HTML5 CODE EXAMPLE: Basic example of using canvas in HTML5
added on May 18, 2012
Basic example of using canvas in HTML5
This creates a canvas that is embedded in a page and upon it with two for loops we draw squares.

<!DOCTYPE html>
<html>
<head>
<title>the test</title>
<script src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function() {
drawIt('rgb(100,100,12)');
$('canvas#stage').click(function() {
drawIt('rgb(200,23,200)');
});
});
function drawIt(theColor) {
var stage = $('canvas#stage')[0].getContext('2d');
for( y = 1; y <= 200; y = y + 12) {
for( x = 1; x <= 200; x = x + 12) {
stage.fillStyle = theColor;
stage.fillRect(x, y, 10, 10);
}
}
}
</script>
<style type="text/css">
body {
background-color: #ddd;
}
canvas#stage {
border: 1px solid #aaa;
cursor: pointer;
cursor: hand;
margin: 7px 0 0 0;
}
div {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div>click on the graphic</div>
<canvas id="stage" width="204" height="204"></canvas>
<div>so that the color changes</div>
</body>
</html>
<html>
<head>
<title>the test</title>
<script src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function() {
drawIt('rgb(100,100,12)');
$('canvas#stage').click(function() {
drawIt('rgb(200,23,200)');
});
});
function drawIt(theColor) {
var stage = $('canvas#stage')[0].getContext('2d');
for( y = 1; y <= 200; y = y + 12) {
for( x = 1; x <= 200; x = x + 12) {
stage.fillStyle = theColor;
stage.fillRect(x, y, 10, 10);
}
}
}
</script>
<style type="text/css">
body {
background-color: #ddd;
}
canvas#stage {
border: 1px solid #aaa;
cursor: pointer;
cursor: hand;
margin: 7px 0 0 0;
}
div {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div>click on the graphic</div>
<canvas id="stage" width="204" height="204"></canvas>
<div>so that the color changes</div>
</body>
</html>
JQUERY CODE EXAMPLE: How to make a simple interactive shooter game
added on May 18, 2012
How to make a simple interactive shooter game
This is the minimal code to make shooter/invader game interaction. There is a ship, you can move the shooter with the arrow keys, and the up arrow shoots. If the laser hits the ship, it disappears.

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var winWidth = $(document).width();
var duration = 1000;
$(document).keydown(function(e) {
var keyCode = e.keyCode || e.which;
var keyMap = {left: 37, up: 38, right: 39, down:40};
switch(keyCode) {
case keyMap.left:
$('img#shooter').animate({
left: '-=50'
}, 200);
break;
case keyMap.right:
$('img#shooter').animate({
left: '+=50'
}, 200);
break;
case keyMap.up:
var shooterLeft = $('img#shooter').offset().left;
var shooterTop = $('img#shooter').offset().top;
$('div#laser').offset({left: shooterLeft+12, top: shooterTop-30});
$('div#laser').show();
$('div#laser').animate({top: 10}, 1000, function() {
var laserLeft = $('div#laser').offset().left;
var shipLeft = $('img#ship').offset().left;
if(laserLeft > shipLeft && laserLeft < shipLeft+80) {
$('img#ship').hide();
}
$('div#laser').offset({left:0, top:0});
$('div#laser').hide();
});
break;
}
});
});
</script>
<style type="text/css">
body {
background-color: #bbb;
}
img#ship {
position: absolute;
top: 10px;
left: 200px;
}
img#shooter {
position: absolute;
top: 90%;
left: 20%;
}
div#laser {
position: absolute;
width: 3px;
height: 30px;
background-color: orange;
display: none;
}
p#instructions {
position: absolute;
top: 92%;
color: #777;
}
</style>
</head>
<body>
<p id="instructions">use arrows to move and shoot</p>
<img id="ship" src="images/ship.png" alt=""/>
<img id="shooter" src="images/shooter.png" alt=""/>
<div id="laser"></div>
</body>
</html>
<html>
<head>
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var winWidth = $(document).width();
var duration = 1000;
$(document).keydown(function(e) {
var keyCode = e.keyCode || e.which;
var keyMap = {left: 37, up: 38, right: 39, down:40};
switch(keyCode) {
case keyMap.left:
$('img#shooter').animate({
left: '-=50'
}, 200);
break;
case keyMap.right:
$('img#shooter').animate({
left: '+=50'
}, 200);
break;
case keyMap.up:
var shooterLeft = $('img#shooter').offset().left;
var shooterTop = $('img#shooter').offset().top;
$('div#laser').offset({left: shooterLeft+12, top: shooterTop-30});
$('div#laser').show();
$('div#laser').animate({top: 10}, 1000, function() {
var laserLeft = $('div#laser').offset().left;
var shipLeft = $('img#ship').offset().left;
if(laserLeft > shipLeft && laserLeft < shipLeft+80) {
$('img#ship').hide();
}
$('div#laser').offset({left:0, top:0});
$('div#laser').hide();
});
break;
}
});
});
</script>
<style type="text/css">
body {
background-color: #bbb;
}
img#ship {
position: absolute;
top: 10px;
left: 200px;
}
img#shooter {
position: absolute;
top: 90%;
left: 20%;
}
div#laser {
position: absolute;
width: 3px;
height: 30px;
background-color: orange;
display: none;
}
p#instructions {
position: absolute;
top: 92%;
color: #777;
}
</style>
</head>
<body>
<p id="instructions">use arrows to move and shoot</p>
<img id="ship" src="images/ship.png" alt=""/>
<img id="shooter" src="images/shooter.png" alt=""/>
<div id="laser"></div>
</body>
</html>
JQUERY CODE EXAMPLE: How to make a click park an image in the corner by using .animate()
added on May 18, 2012
How to make a click park an image in the corner by using .animate()
When you click the page, the image animates on width, height and opacity, and a function is called on completion.

<!DOCTYPE html>
<html>
<head>
<title>how to park a graphic with .animate()</title>
<style type="text/css">
img#alien {
position: relative;
left: 0;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var winWidth = $(document).width();
var duration = 500;
$(document).click(function(event) {
$("#player").animate({
opacity : .1,
width : 100,
height : 100
}, duration, function() {
$('body').css('background-color', 'beige');
$('p#message').html('parked.')
});
});
});
</script>
</head>
<body>
<p id="message">
click anywhere to park the graphic
</p>
<img alt="" id="player" src="images/code.png" style="width: 200px; height: 200px">
</body>
</html>
<html>
<head>
<title>how to park a graphic with .animate()</title>
<style type="text/css">
img#alien {
position: relative;
left: 0;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var winWidth = $(document).width();
var duration = 500;
$(document).click(function(event) {
$("#player").animate({
opacity : .1,
width : 100,
height : 100
}, duration, function() {
$('body').css('background-color', 'beige');
$('p#message').html('parked.')
});
});
});
</script>
</head>
<body>
<p id="message">
click anywhere to park the graphic
</p>
<img alt="" id="player" src="images/code.png" style="width: 200px; height: 200px">
</body>
</html>
JQUERY CODE EXAMPLE: How to display a mouseover message which when clicked disappears
added on May 18, 2012
How to display a mouseover message which when clicked disappears
This example shows a bar on the top, you click it to make it disappear, then click anywhere to make it reappear. There is also a mouseover effect.

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('div#message').click(function(e) {
e.stopPropagation();
$('div#message').fadeOut('fast');
});
$('div#message').mouseover(function(e) {
e.stopPropagation();
$('div#message').css('color', '#999');
$('div#message').css('background-color', '#ccc');
});
$('div#message').mouseout(function(e) {
e.stopPropagation();
$('div#message').css('color', 'black');
$('div#message').css('background-color', 'orange');
});
$(document).click(function(e) {
$('div#message').fadeIn('fast');
});
});
</script>
<style type="text/css">
div#message {
background-color: orange;
width: 100%;
text-align: center;
font-size: xx-large;
cursor: hand;
cursor: pointer;
}
</style>
</head>
<body>
<div id="message">This is the message.</div>
</body>
</html>
<html>
<head>
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('div#message').click(function(e) {
e.stopPropagation();
$('div#message').fadeOut('fast');
});
$('div#message').mouseover(function(e) {
e.stopPropagation();
$('div#message').css('color', '#999');
$('div#message').css('background-color', '#ccc');
});
$('div#message').mouseout(function(e) {
e.stopPropagation();
$('div#message').css('color', 'black');
$('div#message').css('background-color', 'orange');
});
$(document).click(function(e) {
$('div#message').fadeIn('fast');
});
});
</script>
<style type="text/css">
div#message {
background-color: orange;
width: 100%;
text-align: center;
font-size: xx-large;
cursor: hand;
cursor: pointer;
}
</style>
</head>
<body>
<div id="message">This is the message.</div>
</body>
</html>
JQUERY CODE EXAMPLE: Basic template code with (document).ready syntax
added on May 18, 2012
Basic template code with (document).ready syntax
This is one way to load JQuery code (ajax.googleapis.com).

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('p').css('font-size', '45pt');
});
</script>
</head>
<body>
<p>test of document ready</p>
</body>
</html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('p').css('font-size', '45pt');
});
</script>
</head>
<body>
<p>test of document ready</p>
</body>
</html>
JQUERY CODE EXAMPLE: How to save values on a function
added on May 18, 2012
How to save values on a function
Functions are like objects in JavaScript, you can save properties on them as shown here:

<html>
<head>
<title>skdfj</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('p').css('color', 'green');
var fct = function(){};
console.log(typeof fct);
fct.whatever = 'ok';
console.log(fct);
console.log(fct.whatever);
});
</script>
</head>
<body>
<p>alskdfj</p>
</body>
</html>
<head>
<title>skdfj</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('p').css('color', 'green');
var fct = function(){};
console.log(typeof fct);
fct.whatever = 'ok';
console.log(fct);
console.log(fct.whatever);
});
</script>
</head>
<body>
<p>alskdfj</p>
</body>
</html>
JQUERY CODE EXAMPLE: How to move a DIV to the right when you click it
added on May 18, 2012
How to move a DIV to the right when you click it
Each time you click the DIV, it reads its left position and moves itself to the right.

<!DOCTYPE html>
<html>
<head>
<title>text </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).click(function() {
var position_x = $('div#player').css('left');
position_x = parseInt(position_x);
$('div#player').css('left', position_x + 10);
});
</script>
<style type="text/css">
div#player {
position: absolute;
width: 50px;
height: 50px;
background-color: lightgreen;
cursor: pointer;
}
</style>
</head>
<body>
<div id="player"></div>
</body>
</html>
<html>
<head>
<title>text </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).click(function() {
var position_x = $('div#player').css('left');
position_x = parseInt(position_x);
$('div#player').css('left', position_x + 10);
});
</script>
<style type="text/css">
div#player {
position: absolute;
width: 50px;
height: 50px;
background-color: lightgreen;
cursor: pointer;
}
</style>
</head>
<body>
<div id="player"></div>
</body>
</html>
CSS CODE EXAMPLE: How to create colored div icons with text centered vertically and horizontally
added on May 18, 2012
How to create colored div icons with text centered vertically and horizontally
If you want to have different colored icons with dynamic text in the middle, this code will get you started.

<html>
<head>
<style type="text/css">
body {
width: 400px;
}
div.item {
margin: 0 0 20px 0;
}
div.iconArea {
float: left;
margin: 0 5px 0 0;
width: 70px;
height: 70px;
font-size: 10pt;
position: relative;
}
div.iconArea div.iconText {
height: 20px;
position: relative;
top: 50%;
text-align: center;
margin: -10px auto 0 auto;
}
div.infoArea {
margin: 0 0 0 75px;
}
div.infoArea div.title {
font-weight: bold;
}
div.clear {
clear: both;
}
</style>
</head>
<body>
<div class="item">
<div class="iconArea" style="background-color:pink"><div class="iconText" style="color:purple">Info</div></div>
<div class="infoArea">
<div class="title">This is an Info</div>
<div>This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around.
</div>
<div class="clear"></div>
</div>
</div>
<div class="item">
<div class="iconArea" style="background-color:lightgreen"><div class="iconText" style="color:brown">Flashcard</div></div>
<div class="infoArea">
<div class="title">This is a Flashcard</div>
<div>This is the description which will be wrapping around2. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around.
</div>
<div class="clear"></div>
</div>
</div>
<div class="item">
<div class="iconArea" style="background-color:navy"><div class="iconText" style="color:yellow">Question</div></div>
<div class="infoArea">
<div class="title">This is a Question</div>
<div>This is the description which will be wrapping around2. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around.
</div>
<div class="clear"></div>
</div>
</div>
</body>
</html>
<head>
<style type="text/css">
body {
width: 400px;
}
div.item {
margin: 0 0 20px 0;
}
div.iconArea {
float: left;
margin: 0 5px 0 0;
width: 70px;
height: 70px;
font-size: 10pt;
position: relative;
}
div.iconArea div.iconText {
height: 20px;
position: relative;
top: 50%;
text-align: center;
margin: -10px auto 0 auto;
}
div.infoArea {
margin: 0 0 0 75px;
}
div.infoArea div.title {
font-weight: bold;
}
div.clear {
clear: both;
}
</style>
</head>
<body>
<div class="item">
<div class="iconArea" style="background-color:pink"><div class="iconText" style="color:purple">Info</div></div>
<div class="infoArea">
<div class="title">This is an Info</div>
<div>This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around.
</div>
<div class="clear"></div>
</div>
</div>
<div class="item">
<div class="iconArea" style="background-color:lightgreen"><div class="iconText" style="color:brown">Flashcard</div></div>
<div class="infoArea">
<div class="title">This is a Flashcard</div>
<div>This is the description which will be wrapping around2. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around.
</div>
<div class="clear"></div>
</div>
</div>
<div class="item">
<div class="iconArea" style="background-color:navy"><div class="iconText" style="color:yellow">Question</div></div>
<div class="infoArea">
<div class="title">This is a Question</div>
<div>This is the description which will be wrapping around2. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around. This is the description which will be wrapping around.
</div>
<div class="clear"></div>
</div>
</div>
</body>
</html>
JAVASCRIPT CODE EXAMPLE: How to write a recursive function
added on May 18, 2012
How to write a recursive function
This is a simple example of a function calling itself to calculate a value.

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript">
window.onload = function() {
function calculate(num) {
if(num == 0) {
return 1;
} else {
return num * calculate(num - 1);
}
}
console.log(calculate(0));
console.log(calculate(1));
console.log(calculate(2));
console.log(calculate(3));
console.log(calculate(4));
}
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<title>test</title>
<script type="text/javascript">
window.onload = function() {
function calculate(num) {
if(num == 0) {
return 1;
} else {
return num * calculate(num - 1);
}
}
console.log(calculate(0));
console.log(calculate(1));
console.log(calculate(2));
console.log(calculate(3));
console.log(calculate(4));
}
</script>
</head>
<body>
</body>
</html>
JQUERY CODE EXAMPLE: How to use the .addClass() method in jQuery
added on May 18, 2012
How to use the .addClass() method in jQuery
When the user clicks on the vocabulary term, the class changes.

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function() {
$('span.vocabulary').click(function() {
$(this).addClass('highlight');
});
});
</script>
<style type="text/css">
span.vocabulary {
cursor: pointer;
cursor: hand;
color: green;
border-bottom: 1px dashed #555;
}
span.highlight {
background-color: yellow;
font-size: 18pt;
color: navy;
border-bottom: none;
}
</style>
</head>
<body>
<p>The staff no longer has to work with complex and <span class="vocabulary">unwieldy</span> control flags.</p>
</body>
</html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function() {
$('span.vocabulary').click(function() {
$(this).addClass('highlight');
});
});
</script>
<style type="text/css">
span.vocabulary {
cursor: pointer;
cursor: hand;
color: green;
border-bottom: 1px dashed #555;
}
span.highlight {
background-color: yellow;
font-size: 18pt;
color: navy;
border-bottom: none;
}
</style>
</head>
<body>
<p>The staff no longer has to work with complex and <span class="vocabulary">unwieldy</span> control flags.</p>
</body>
</html>
JQUERY CODE EXAMPLE: How to put JavaScript/JQuery at end of Body
added on May 18, 2012
How to put JavaScript/JQuery at end of Body
If you put the JavaScript block at the end of the body element, then you don't have to use the $(document).ready() function, which makes your code simpler. And in most browsers, the user will have a faster loading experience especially on large pages.

<!DOCTYPE html>
<html>
<head>
<title>Test: JavaScript at end of Body Element</title>
</head>
<body>
<p>test</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$('p').css('color','red');
</script>
</body>
</html>
<html>
<head>
<title>Test: JavaScript at end of Body Element</title>
</head>
<body>
<p>test</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$('p').css('color','red');
</script>
</body>
</html>
JQUERY CODE EXAMPLE: How to use insertBefore(), .length, and .filter()
added on May 18, 2012
How to use insertBefore(), .length, and .filter()
Note also that you select within a context with a second parameter like this: $('p', 'div#specialArea').length.

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.highlight {
color: navy;
font-weight: bold;
font-size: 18pt;
}
</style>
</head>
<body>
<p>one</p>
<p class="highlight">two</p>
<p>three</p>
<div id="contentMarker"/>
<div id="messageMarker"/>
<div id="specialArea">
<p>new1</p>
<p class="highlight">new2</p>
</div>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$('<p>four</p>').insertBefore('div#contentMarker');
$("<div>There are " + $('p').length + " paragraph elements</div>").insertBefore('div#messageMarker');
$('<p>five</p>').insertBefore('div#contentMarker');
$("<div>And there are now " + $('p').length + " paragraph elements</div>").insertBefore('div#messageMarker');
$("<div>there are " + $('p', 'div#specialArea').length + " in the special area</div>").insertBefore('div#messageMarker');
var paragraphs = $('p');
$("<div>there are now " + paragraphs.length + " paragraphs</div>").insertBefore('div#messageMarker');
$("<div>but there are only " + paragraphs.filter('.highlight').length + " highlighted paragraphs</div>").insertBefore('div#messageMarker');
</script>
</body>
</html>
<html>
<head>
<style type="text/css">
.highlight {
color: navy;
font-weight: bold;
font-size: 18pt;
}
</style>
</head>
<body>
<p>one</p>
<p class="highlight">two</p>
<p>three</p>
<div id="contentMarker"/>
<div id="messageMarker"/>
<div id="specialArea">
<p>new1</p>
<p class="highlight">new2</p>
</div>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$('<p>four</p>').insertBefore('div#contentMarker');
$("<div>There are " + $('p').length + " paragraph elements</div>").insertBefore('div#messageMarker');
$('<p>five</p>').insertBefore('div#contentMarker');
$("<div>And there are now " + $('p').length + " paragraph elements</div>").insertBefore('div#messageMarker');
$("<div>there are " + $('p', 'div#specialArea').length + " in the special area</div>").insertBefore('div#messageMarker');
var paragraphs = $('p');
$("<div>there are now " + paragraphs.length + " paragraphs</div>").insertBefore('div#messageMarker');
$("<div>but there are only " + paragraphs.filter('.highlight').length + " highlighted paragraphs</div>").insertBefore('div#messageMarker');
</script>
</body>
</html>
JQUERY BOOK NOTES: Wrox Professional jQuery (April 2012) | 4.1
added on May 18, 2012
Wrox Professional jQuery (April 2012)
- chap1, getting started: some useful tools;1.1
- chap2, javascript primer;2.6
- basics, scope, applying modules, prototype, best practicies, ajax post
- chap3, jquery core;2.3
- structure, basics, utility functions: isFunction, noop, makeArray(),map() like each(), unobstrusive javascript, anonymous functions, chaining,how jquery is more consise, looks into jquery code, looks how $.ready() works, using jquery with other libraries, nice url reference at end
-lookup: cody lindley
- chap4, DOM Element Selection and Manipulation;2.2
- shows how jquery is quicker, $ and JQuery, uses html5 doctype, has easier selection: http://code.jquery.com/jquery-1.7.1.js, selecting elements by class, ancestor decendent, var allDivs = $('div[id^="area"]');, also $("[attributeName*='value']");, selecting by position, shows :input, and all those like :checked, etc., and p:contains, also var allDivs = $('div:contains("ok")');, shows :has(), and :parent, even white space is considered children, custom user selectors, how to use find:, shows var secondEl = listElements.get(2);, shows index(), shows toArray(), good example with fitler/end, shows andSelf(), shows text() which combines text of all elements, text() works with both XML and HTML, and html() only first matched element, removeAttr(), and appendTo().
- chap5, Event Handling;3.4
- good history of DOM level 0, 2, and IE model, netscape navigator 2, stopPropagation() and such, microsoft did bubbling different, shows bind(), you can also use live() (if element does not exist), live() cannot be chained, also unbind(), die(), undelegate(), for clicking only once one(), shows that bind and click can do same thing, good example of fadin, fadout, has form example, $(function(){...); as you'll recall is equivalent to using .ready(), good example of .each building a LI list, new event api with 1.7, instead of .bind() and .unbind(), .live() and .die() and set .click() and .blur(), you have .on() and .off(), two ways to use on()
- chap6, html forms;5.0
- data, and ajax: jQuery's .data() method, which stores arbitrary data for an element with a meaningful key, shows setField, talks about microsoft's three technologies, shows how to use modernizr, shows control types URL, email, telephone, etc. in HTML5, jquery place holder prjoect, this is also a focus example, shows raw ajax, then shows .ajax (we used .post), shows how to parse a document coming via ajax, also shows how to do it with getJSON, there is unfortunately no postJSON(), shows how .get(...) is shorthand for .ajax(), and .post() which is what I use in my language apps, also .load() is useful and is attached to element, then does form with placeholder="First Name" and required as attributes, modernizr makes sure they are present which is an example for load.
- chap7, animations and effects;4.8
- shows how to animate a box moving right on click, then shows offset(), talks about hide() and show(), talks about slideDown, slideUp, has example of this, uses height() and width() so that the px does not come with it, shows how to animate with animate, has a little space invader game, talks about canvas, recommended http://diveintohtml5.info/canvas.html.
- chap8, jquery UI making look slick;4.2
- shows how to setup jqueryui, prettier buttons, tabs, accordian, but doesn't really tell how to set them up, autocomplete, datepicker, lots of parameters, dialog, progressbar, slider
- foray: try to get all jqueryui examples to work here; 3.2
- chap9, jquery UI mouse interactions;4.1
- dragging and dropping, has example, sorting with example, you can resizing with example, selectable wiht example,
- foray: try to get all jqueryui examples to work here; 3.1
- chap10, writing effective jquery code;2.9
- best practices, minimize dom updates (reflows and repaints), has speed test (tables/rows), leverage dom hyperspace (do all in javascript), careful with $.each, use Array.ForEach(), caching objects, document.querySelectorAll is fast, careful of jquery-unique selectors e.g. :file, give selectors a context, skip jquery selectors and simply use e.g. document.getElementById('baz').href, Don't Repeate Yourself, use e.g. javascript singleton, ***code in framework structure, code for "dashbaord module", using html5 data attributes instead of css classes and ids, use $.data(), something about data API
- todo: do number of examples with $.each();4.3
- todo: do code example with .this and .that and learn background;3.2
- todo: learn hasClass();4.5
- read: https://developer.mozilla.org/en/Writing_Efficient_CSS; classic article on efficient css;2.1
- todo: do code example of all jquery selectors e.g. ":file", ":odd", etc.; 4.3
- todo: do code examples of javascript patters e.g. singleton;4.3
- todo: set up simple framework as in this chapter, page 209;4.5
- foray: get old framwork code, set it up again and get into github;2.3
- foray: crack github get project in, fork, etc.;4.9
- foray: learn module pattern and record as code example: http://www.yuiblog.com/blog/2007/06/12/module-pattern;4.3
- foray: get example with $.data() going;4.2
- chap11, jquery templates;2.1
- mentions template engines Freemarker or Mustache, this looks like a good chapter on a good pattern for jquery development, jquery templates started out in march 2010, as of april 2011, activity on the jquery template plugin stopped, leaving it permanently in that beta state, mentions Templating, Data Link, and Globalization, seems work has stopped but "it's therefore sensible to leverage the existing plugin until the newer effort is mature enough to supplant it", uses , also in javascript with $.template(), shows how, shows how to apply with $.tmpl(), using remote data, adding log to templates like if/then and each, ends with an example how to do one
- foray: spend 30 minutes with http://freemarker.sourceforge.net;2.9
- question: what is the sense or a use case for javascript/jquery templates?;4.3
- chap12, writing jquery plugins;3.1
- naming convention jquery.pluginName.js, two patterns to extend: jquery.fn and jQuery.extend(), jquery ui widget factory, $ should point to jquery, return jquery object whenever possible, best practices, provide public access, widget factory again,
- quote: to do a basic version doesn't mean it's easy to do it right;3.1
- todo: spend 1 hour looking through the jquery source and take notes;3.6
- quote: semicolons are your friend;javascript;4.1
- quote: Relying on implicit insertion can cause subtle, hard to debug problems. Don't do it. You're better than that.;38;javascript
- foray: create a jquery plugin (just do the one on page 259 here);4.3
- chap13, advanced asynchronous programming with jquery deferred;1.1
- $.deferred, introduced in version 1.5, is a chainable utility object that provides ? ne-tuned control over the way callback functions are handled, a promise is a proxy for the result of an action, has example, gets quick complicated
- chap14, unit testing;2.1
- introduces qunit, differences between xunit and qunit, asynchronous tests, using Using asyncTest, mocking ajax requests, has good example of test suite
- foray: get qunit up and running: http://docs.jquery.com/QUnit;3.6
- fc: two unit testing apps for jquery;xunit and qunit;3.1e
- todo: do test suite here page 300;3.1
EXTJS CODE EXAMPLE: Mimimum extjs4 application
added on May 16, 2012
Mimimum extjs4 application
This is the minimum application for extJS4 after taking out as many directories as I could, still 2000+ files to upload to FTP (see jsbuilder) and it runs slowly, need to resolve that. But for local development, this would be the code to start with.

app.js
var title1 = 'Spanish';
var content1 = "<ul class='list'>\
<li>uno</li>\
<li>dos</li>\
<li>tres</li>\
</ul>";
var title2 = 'French';
var content2 = "<ul class='list'>\
<li>un</li>\
<li>deux</li>\
<li>troiss</li>\
</ul>";
Ext.application({
name: 'HelloExt',
launch: function() {
var childPanel1 = Ext.create('Ext.panel.Panel', {
title: title1,
html: content1,
bodyStyle: 'padding: 10px'
});
var childPanel2 = Ext.create('Ext.panel.Panel', {
title: title2,
html: content2,
bodyStyle: 'padding: 10px'
});
Ext.create('Ext.container.Viewport', {
items: [ childPanel1, childPanel2 ]
});
}
});
var content1 = "<ul class='list'>\
<li>uno</li>\
<li>dos</li>\
<li>tres</li>\
</ul>";
var title2 = 'French';
var content2 = "<ul class='list'>\
<li>un</li>\
<li>deux</li>\
<li>troiss</li>\
</ul>";
Ext.application({
name: 'HelloExt',
launch: function() {
var childPanel1 = Ext.create('Ext.panel.Panel', {
title: title1,
html: content1,
bodyStyle: 'padding: 10px'
});
var childPanel2 = Ext.create('Ext.panel.Panel', {
title: title2,
html: content2,
bodyStyle: 'padding: 10px'
});
Ext.create('Ext.container.Viewport', {
items: [ childPanel1, childPanel2 ]
});
}
});
index.htm
<html>
<head>
<title>extjs test1</title>
<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
<script type="text/javascript" src="extjs/ext.js"></script>
<script type="text/javascript" src="app.js"></script>
<style type="text/css">
ul.list li {
color: navy;
list-style: disc;
margin: 0 0 0 30px;
}
</style>
</head>
<body></body>
</html>
<head>
<title>extjs test1</title>
<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
<script type="text/javascript" src="extjs/ext.js"></script>
<script type="text/javascript" src="app.js"></script>
<style type="text/css">
ul.list li {
color: navy;
list-style: disc;
margin: 0 0 0 30px;
}
</style>
</head>
<body></body>
</html>
JQUERY BOOK NOTES: Oreilly jQuery Cookbook (Nov 2009) | 4.8
added on May 16, 2012
Oreilly jQuery Cookbook (Nov 2009)
- chap1, where to put jquery, the $(document).ready() event, lots of selectors, filter, end(), andSelf(), next(), prev(), parent(), remove() but they stay as well, replaceWith(), clone(),
- quote: Any obstacle that I've encountered during my development by placing JavaScript at the bottom of the page has been easily overcome and well worth the optimization gains.
- learn: end()
- try: $('ul#test li')
- try: replace a href with .attr(), page 29-30
- todo: record 1.17: avoid global conflicts
- chap2, direct descendent (>), .children(), .siblings(), nextAll(), also the tilda, index selectors (eq, lt, etc.), hmm, adding class "even" for css, nice, :animated, :contains(), :not
- try: example with :animated
- code: page 42, filter with regex
- code: :hidden()
- code: match attribute, also :checkbox, :password
- code: 2.10
- chap3, looping, eq(), get() not get, get the index, finds query
- code: page 61 example;4.6
- code: do 3.4 with getting index;4.5
- code: 3.5 with .map();4.7
- code: 3.6 with .wrap();4.6
- code: do 3.7 nonconflict with prototype;2.9
- code: 3.8 plugin;4.9
- chap4, jquery.support, in 1.3, isFunction,
- code: 4.2 iterating over arrays; 4.7
- code: 4.3 jquery.grep;4.6
- code: 4.4 map;4.6
- code: 4.5 merge;4.2
- code: 4.6 unique;4.2
- code: 4.8 trim;3.9
- code: 4.9 using data as code practice;4.8
- chap5, plugin for external function, custom iterator, profiling, caching objects, #foo is faster than .foo, loading tables faster, for loops faster than each, never use a for..in loop to iterate over a jquery object or an array of any type, tips to increase speed, innerHtml faster than html(), use uncompressed jquery code and step in, minimize number of http requests, support javascript off,
- code: try with setTimeOut, 5.2;4.2
- code: 5.3 redundent repetition pattern;4.5
- code: 5.7 toggle attribute;3.5
- foray: get the # URL updater to work in jquery;4.9
- code: with focus again;4.3
- chap6, width/height of window, of element, also the offset, with .position() and .offset(), scrolling the window, determining if elemnt is in view port, changing relative to absolute, positining reltaive to another,
- code: centering in viewport, 6.6;4.5
- code: 8.6 switching stylesheets based on browser width;3.7
- chap7, simultaneous sliding/fading, determine if elements are being animated, stopping and restarting animations,
- code: sliding and fading 7.1;4.5
- code: 7.2 slide up;4.5
- code: 7.3 horizontal accordian;4.5
- code: 7.8 custom easing effects;4.5
- chap8, events, event.stopPropagation, e.preventDefault, event.target, avoid multiple hover,
- code: 8.1 and 8.2 pattern: attach many events to one handler (pass e);4.2
- code: 8.4 figure out the namespace thing;4.1
- code: 8.5 pass extra data to handlers;4.1
- code: 8.6 accessing before document load;3.9
- chap9, advanced events,
- code: 9.2 understand global event triggering;3.5
- code: 9.3 create you own events;4.9
- code: 9.5 event driven plugins;4.3
- code: 9.6 understand broadcast;4.0
- chap10, html form enhancements,
- code: 10.1 focus quick;5.0
- code: 10.3 radio buttons;4.5
- code: 10.4 and 10.5 checkboxes;4.5
- code: 10.5 adding/removing select options;4.8
- code: 10.7 autotabbing;4.1
- code: 10.8 display character count (uses bind);4.9
- code: 10.9 constraining to specific characters;4.7
- code: 10.10 ajax form (see if different);4.4
- code: 10.11 validating forms;4.5
- chap11, form enhancements with plugins, spinner widget,
- code: 11.1 validating forms;4.6
- code: 11.2 masked input fields;4.5
- code: 11.3 autocomplete text fields with jquery UI;5.0
- code: 11.4 range of values, with jquery UI;4.8
- code: 11.6 uploading files in background;4.9
- code: 11.7 max length;4.8
- code: check out 11.8;4.2
- code: datepicker 11.10, get working with standard date syntax e.g. 2012-05-09;5.0
- chap12, plugins, search and install, when to write, private functions in plugin, metadata plugin, static function
- foray: search and install plugins from various sources;4.7
- code: write pluging 12.3;4.8
- code: passing options to custom plugin 12.4;4.6
- chap13, interface components
- code: custom tool tip13.1;5.0
- code: filetree expander 13.2;3.5
- code: according 13.3;4.8
- code: 13.4 tabbing;4.7
- code: 13.5 modal window;4.6
- code: 13.6 drop down menus;4.6
- code: 13.7 crossfading roating images (for run site);5.0
- code: 13.8 sliding panels;4.8
- chap14, user interfaces, jquery plugins settings, jqueryUI events, etc.
- code: include jquery ui entire;4.8
- code: include one jqueryUI component;4.9
- code: audio plaer 14.10, built into flashcards, etc.;5.0
- chap15, jqueryui theming, long explanation, theme roller, overriding, mulitple themes on one page,
- chap16, data formats and ajax, .ajaxSetup,
- code: 16.1 jquery ajax;5.0
- code: 16.3 user feedback while processing, see if same;4.7
- code: 16.4, 16.5 json/html;4.5
- code: 16.6 converting XML to DOM;4.9
- code: 16.7, 16.8 creating/parsing JSON, see if same;4.6
- code: 16.9, JSONP get to work with two dpod sites;5.0
- chap17, large projects, queuing requests
- code: 17.1 client-side storage, try it;4.9
- code: 17.2 saving application state;4.5
- code: 17.4 understand javascript templating engine;4.8
- code: 17.6 get example with back button;4.4
- chap18, unit testing, keylogger, keeping test atomic, grouping,
JAVASCRIPT CODE EXAMPLE: JavaScript example of simple arrays and interating through arrays and object properties
added on May 16, 2012
JavaScript example of simple arrays and interating through arrays and object properties
Notice how to define multiple line variables with '\' at the end of the line.

index.htm
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style type="text/css">
div#content {
width: 300px;
background-color: #eee;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
div.firstLine {
padding: 0 0 5px 0;
}
div.line {
padding: 0 0 5px 0;
border-top: 1px solid #ccc;
}
</style>
</head>
<body>
<div id="content"></div>
<script type="text/javascript">
//insert text in element
var message = 'hello';
displayIt('first line', 'firstLine');
//simple arrays
var names = [ 'jim', 'joe', 'john' ];
displayIt('and the names are ' + names.join(', '));
displayIt('the second name is ' + names[1] + ' and there are ' + names.length + ' names');
//iteration
displayIt('the names are listed here:');
for(var i = 0; i <names.length; i++) {
displayIt(names[i]);
}
//array object
names_object = {
0 : 'hal',
1 : 'hank',
2 : 'howard'
}
displayIt(names_object[1]);
for(var key in names_object) {
var obj = names_object[key];
displayIt(key + '/' + obj);
}
function displayIt(text, className) {
var text = arguments.length < 1 ? '(default text)' : text;
var className = arguments.length < 2 ? 'line' : className;
var elContent = document.getElementById('content');
elContent.innerHTML += '<div class="'+className+'">' + text + '</div>';
}
</script>
</body>
</html>
<html>
<head>
<title>test</title>
<style type="text/css">
div#content {
width: 300px;
background-color: #eee;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
div.firstLine {
padding: 0 0 5px 0;
}
div.line {
padding: 0 0 5px 0;
border-top: 1px solid #ccc;
}
</style>
</head>
<body>
<div id="content"></div>
<script type="text/javascript">
//insert text in element
var message = 'hello';
displayIt('first line', 'firstLine');
//simple arrays
var names = [ 'jim', 'joe', 'john' ];
displayIt('and the names are ' + names.join(', '));
displayIt('the second name is ' + names[1] + ' and there are ' + names.length + ' names');
//iteration
displayIt('the names are listed here:');
for(var i = 0; i <names.length; i++) {
displayIt(names[i]);
}
//array object
names_object = {
0 : 'hal',
1 : 'hank',
2 : 'howard'
}
displayIt(names_object[1]);
for(var key in names_object) {
var obj = names_object[key];
displayIt(key + '/' + obj);
}
function displayIt(text, className) {
var text = arguments.length < 1 ? '(default text)' : text;
var className = arguments.length < 2 ? 'line' : className;
var elContent = document.getElementById('content');
elContent.innerHTML += '<div class="'+className+'">' + text + '</div>';
}
</script>
</body>
</html>
PHP BOOK NOTES: Smarty (2006) | 3.5
added on May 15, 2012
Smarty (2006)
- chap1,
- chap2,
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
JAVASCRIPT BOOK NOTES: Packtpub ExtJS4 First Look (Jan 2012) | 3.9
added on May 15, 2012
Packtpub ExtJS4 First Look (Jan 2012)
- chap1, biggest overhaul, namespaces, extjs3 namespace compatible, shows base code, has jsbuilder in it, ok but not in mine, talks about all files, class system more object oriented, backward compatible, Ext.extend is deprecated, much more like classes, config so you can use getTitle, nice, has statics so don't need to instantiate, sandboxed means it runs next to extjs3, new features: forms, grids, layouts;3.5
- lookup: http://loianegroner.com, author site
- lookup: http://neiliscoding.blogspot.com, reviwer site
- lookup: reviewer site, french: http://www.papdevis.fr and http://olivierpons.fr
- chap2, new data package, model class, data package shared with sencha touch, 3 was record, 4 is model, 4 does not support record class, shows how to create an object, talks about types, you can save with .save() but where is it saved? extjs4 three new proxies, nice: proxytype: local storage, ie7 says localstorage not available, sessionStorage proxy, connects to datasource, nice, ajaxProxy is the most-used proxy, properties become attributes in the rest url line, sorters, you have to decode it on the server side, you can write a filter to change the way the URL is created, the syntax, rest proxy (type: 'rest'), jsonp proxy, readers decode data from server, writers send data to server, JsonWriter, sorting, filtering (like WHERE);4.1
- fc: what are the proxies in extjs4?;
- chap3, layouts, improved in 4, autolayout, anchor layout (resizing), absolute layout, hbox layout, vbox layout, accordian, table, column, fit, card, border, components, dock;3.2
- chap4,
- chap5,
- chap6,
- chap7,
DEVELOPER BOOK NOTES: Version Control for Web Developers (Mar 2012) | 3.8
added on May 7, 2012
Version Control for Web Developers (Mar 2012)
- chap1, wamp server 2, how to set up, windows, mac, uses mamp, mamp pro $59, also shows ubuntu;4.8
- chap2, explains version control, history sccs 72, rcs 82, branches, pvcs 85, cvs 1990, clearcase 92, vss 94, perforce, accurev, bitkeeper;2.6
- chap3, SVN, Git, Mercurial (current players), svn 2000, mercurial 2005, git 2005, talks about compiling, explains svn, windows, mac, xcode, also homebrew for mac, then ubuntu, gets svnX, then explains mercurial, how to compile it, sude make install clean, create new repository, explain mercurial: windows, mac, ubuntu, how git is different: git used to be hard on windows but not msysgit, on mac, ubuntu and compiling from source;4.9
- chap4, mentions ways of doing version control: dropbox, external drives, etc., ability to work on different machines, history, clients will want past versions, comments, merging, branching, bridging (between svn and git);3.8
- chap5, non command line options: tortoisesvn, much about it, revert, etc., Syncro SVN client, Versions (for Mac), blame, cornerstone, UNIX: RabbitVCS, then Mercurial: TortoiseHg, Hg Workbench, Mac: MacHg, SourceTree, Git GUI is not the best, windows, no automatic change detection, TortoiseGit, GitHub for Mac, tower, mentions stash
- chap6, version control not for all files, zovo.co not free, amazon cloud drive, also dropbox, sharepoint, magnet svn for office docs,
- try: zovo.co, cloud storage;2.7
- try: amazon cloud drive, free 5GB;4.8
- try: zumodrive.com;3.3
- lookup: pixelnovel, photoshop, adobe drive 3 ;3.8
- try: evolphin.com, version control for other files;3.9
- chap7, svn with notepad++, visual studio, textmate and svn, Coda, BBEdit on mac, neither eclipse nor aptana have version control by default, latest version of aptana comes with git support baked in, can install mercurial manually, netbeans, sublime text 2,
- lookup: Coda;3.1
- foray: setup SVN on Netbeans;4.4
- chap8, shows how to deal with conflicts in all three apps
- chap9, vi and nano on mac and linux, how to do everything on command line, good chapter, lots of detail; 4.6
- foray: setup ubuntu in virtual machine;4.9
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
JQUERY BOOK NOTES: jQuery Mobile Up and Running (Feb 2012) | 4.1
added on May 7, 2012
jQuery Mobile Up and Running (Feb 2012)
- chap1, why mobile platform, myths, it's a UI layer on top, don't need javascript necessarily, comparable to jqueryUI on the desktop side, five categories of mobile devices: mobile phones (no web), low-end mobile devices (very basic web), social devices (gisis phone), smartphones (android/iphone), tablets, lists various OSs and browers, shows compatibility, good
- foray;get jquery mobile app up and running;4.7
- link;http://mobilehtml5.org;html5 compatibility for mobile browsers
- foray;get base mobile jquery code to work on page 16;
- chap2,
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,