Skip to content

Instantly share code, notes, and snippets.

@shultzc
Created March 14, 2012 23:50
Show Gist options
  • Save shultzc/2040478 to your computer and use it in GitHub Desktop.
Save shultzc/2040478 to your computer and use it in GitHub Desktop.
Demo of elementary JavaScript DOM manipulation and event handling
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html version="-//W3C//DTD XHTML 1.1//EN"
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/1999/xhtml
http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd">
<head>
<style type="text/css">
#contentContainer {
border-style: dotted;
}
#outputContainer {
background-color: #ffff99;
}
.highlighted {
background-color: #ffff00;
}
</style>
<script type="text/javaScript">
function populateBases() {
var selectedValue = document.getElementById("ContentPicker").value;
var output;
switch (selectedValue) {
case "1":
output = "adenine, guanine";
break;
case "2":
output = "cytosine, thymine, uracil";
break;
default:
output = "Please select a category of bases above."
break;
}
document.getElementById("outputContainer").innerHTML = output;
}
function addRow() {
var tableElement = getExpandableTableAndCreateIfNeeded();
var newRow = document.createElement('tr');
tableElement.appendChild(newRow);
var rowCount = tableElement.children.length;
var newCell = document.createElement('td');
newCell.innerHTML = "A row (number " + rowCount + ") - click to toggle highlight";
newRow.appendChild(newCell);
var toggleRowSelection = function() {
if (this.className == "" || this.className == null) {
this.className = "highlighted";
}
else {
this.className = null;
}
};
newCell.addEventListener("click", toggleRowSelection);
}
function getExpandableTableAndCreateIfNeeded() {
var table = document.getElementById("expandableTable");
if (table == null) {
table = document.createElement('table');
table.id = "expandableTable";
document.getElementById("tableContainer").appendChild(table);
}
return table;
}
</script>
<title>JavaScript Test</title>
</head>
<body onload="populateBases()">
<h1>Dynamic Bases</h1>
<div id="contentContainer">
<select id="ContentPicker" name="ContentPicker" onchange="populateBases()">
<option value="0">select a nitrogenous base</option>
<option value="1">purines</option>
<option value="2">pyrimidines</option>
</select>
<div id="outputContainer">
Please enable JavaScript.
</div>
<div id="buttonContainer" style="padding-top: 2em;">
<input type="button" value="Add some content" onclick="addRow()" />
</div>
<div id="tableContainer">
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment