Quick reference for HTML JS and CSS
Date: April 7th 2016
Last updated: April 9th 2016
Following on from html modal popup windows I realised there were a few things that I need to reference on occasion for HTML JS and CSS. As this is a scrapbook for Python I decided to compile a one-pager here rather than writing a whole chapter.
using font styles selected from https://www.google.com/fonts
<head>
<link href='https://fonts.googleapis.com/css?family=Ubuntu|Oswald' rel='stylesheet' type='text/css'>
<style>
h1 {color:red; font-family: 'Oswald';}
p {color:blue; font-family: 'Ubuntu';}
</style>
</head>
Add image with a href
<div id='header-logo'>
<!-- add an anchor tag -->
<a href='../index.html'>
<!-- add the image -->
<img id="homeicon" src="../img/Home-icon.png" alt="Home">
</a>
</div>
Make an image go semi-transparent on mouse-over
/* CSS */
/* note the reference to id in the html: homeicon */
img#homeicon:hover{
opacity: 0.5;
-webkit-opacity: 0.5; /* these add the function for other browsers */
-moz-opacity: 0.5;
filter: alpha(opacity=50);
}
add a button
<head>
<!-- link to my stylesheet -->
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<!-- include bootstrap 3 css -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<!-- snipped -->
<div>
<!-- use a class defined by bootstrap -->
<a href='pages/healthapp.html' class="btn btn-primary">My App</a>
</div>
use JavaScript to switch images when clicked
<head>
<script src="js/jquery-1.11.3.min.js"></script>
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("image1")) {
image.src = "img/image1.png";
} else {
image.src = "img/image2.png";
}
}
</script>
</head>
<body>
<div>
<img id="myImage" onclick="changeImage()" src="img/image1.png">
</div>
</body>
Change an image corresponding to an html dropdown box
<head>
<script>
function myFunction() {
// get the form object from the DOM
var x = document.getElementById("frm1");
// if the select box with id="images" chooses option IMG1...
// note the reference to "value" which is assigned in the dropdown box
if(x.images.value == "IMG1"){
// modify the source attribute to a new image
// I have my images stored in a folder called 'img'
$('img#ImageLocation').attr("src","img/Image1.png")
}
// if the select box with id="images" chooses option IMG2...
else if (x.images.value == "IMG2") {
$('img#ImageLocation').attr("src","img/Image2.png")
}
}
</script>
</head>
<body>
<div>
<form id="frm1" method="post">
<p>
<div>
<label>Image selector:</label>
<!-- call to javascript everytime the dropdown box changes -->
<select id="images" onchange="myFunction()">
<option value="IMG1">Image 1</option>
<option value="IMG2">Image 2</option>
</select>
</div>
</form>
<p>
<!-- provide a button to implement the form selection -->
<!-- note that this button is a double-up to the image selector above
I have left it here because I may want to add more input fields and
subsequently want to execute the JS at the same time as 'submiting'
other content -->
<button onclick="myFunction()">show image</button>
</p>
</div>
<div>
<!-- provide a location for the image to go. Note that
I have added image1 which will be shown when the page is loaded
The select box will typically load the first option which
coincidently matches my choice of image1 below. If the select box
happens to start with option2 then image2 should be loaded first. -->
<img id="ImageLocation" src="../img/Image1.png">
</div>
</body>
form validation - update html only if conditions are met
solutions from http://www.w3schools.com/js/js_comparisons.asp and https://en.wikipedia.org/wiki/Short-circuit_evaluation
<script>
function myFunction() {
// get the dom form object
var x = document.getElementById("frm1");
// Extract the values for each measurement
// Also split each string on white space
var l = x.len.value.split(" ");
var w = x.wid.value.split(" ");
var t = x.thick.value.split(" ");
// parse the form input boxes
// these functions are omitted here
// they basically convert a string to decimal
var len = parse_length(l)
var wid = parse_strings(w)
var thick = parse_strings(t)
// snipped - in here was a calculation of volume
// return the volume to the html tag "demo"
// note the use of shortcut operator "&&"
// The point of this is to only provide volume in the html if
// all of the input boxes contain something
if(x.len.value != "" && x.wid.value != "" && x.thick.value != ""){
document.getElementById("demo").innerHTML = volume;
}
else{
document.getElementById("demo").innerHTML = "";
}
}
</script>
rounding with javascript
solutions from http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript
Math.round(volume) //rounds to whole number
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
volume.toFixed(3) // rounds to a set number of decimals
+volume.toFixed(3) // the + sign drops zeros from the end
//if volume is type text
var volume = "123.789"
parseFloat(volume).toFixed(3); //parse and set decimal level
//round up
Math.ceil(num * 100)/100;
using colors with CSS
http://www.w3schools.com/cssref/css_colors.asp
<p id="myColorfulText" style="color: #3366CC"></p>
Storing data with JavaScript
I want to save the users form input so that I can add to the html document with a current estimate of volume versus their last estimate.
<script>
var myArray = []
function myFunction() {
// get the dom form object
var x = document.getElementById("frm1");
// snipped - the code parsed user input
// and returned an estimate of volume
// the input fields are id'd by len, wid, thick
// return volume to the html tag ONLY if all fields are entered
if(x.len.value != "" && x.wid.value != "" && x.thick.value != ""){
document.getElementById("demo").innerHTML = volume + ' litres';
// save each calculation to the empty array outside this function
// This gets wiped on page reload
// note that the new array item can be accessed by the next index value
// create the string and push to empty array...
myArray.push(x.boards.value + '; length: ' + x.len.value + '; width: ' +
x.wid.value + '; thickness: ' + x.thick.value + ' = ' + volume)
// use the length of the array to annotate html
// when the user clicks the button a second time
// remember that JS is zero indexed
// myArrayLength starts with one due to the previous line
myArrayLength = myArray.length - 1
console.log(myArrayLength)
// on the second request show the last calculation
if(myArrayLength >= 1){
// add a title
document.getElementById("last_calc").innerHTML = "Your last calculation: "
// add the contents of myArray
document.getElementById("myLastCalculation").innerHTML = myArray[myArrayLength-1]
}
}
else{
document.getElementById("demo").innerHTML = "";
}
}
</script>
Add a calculation button in the middle of a form
<script>
function myFunction() {
// snipped
return volume;
}
function myFormFunction(){
var vol = myFunction();
var x = document.getElementById("frm1");
// set form element to the value returned from myFunction
x.elements['vol'].value = vol;
}
</script>
</head>
<body>
<form id="frm1" method="post">
<p>
<div>
<label>Board type:</label>
<!--<input id="boardtype" list="boards">-->
<select id="boards" onchange="myFunction()">
<option value="HP">selection1</option>
<option value="FHP">selection2</option>
</select>
</div>
<div>
<label for="id_length">Length:</label>
<input id="len" type="text" maxlength="100"/>
</div>
</p>
<p>
<div>
<label for="id_width">Width:</label>
<input id="wid" type="text" maxlength="100"/>
</div>
</p>
<p>
<div>
<label for="id_thickness">Thickness:</label>
<input id="thick" type="text" maxlength="100"/>
</div>
</p>
<p>
<div>
<label for="id_volume">Volume:</label>
<input id="vol" type="text" maxlength="100"/>
<!-- Use input to add a button -->
<input type="button" name="calculatevolume" value="calculate"
onclick="myFormFunction();" />
</p>
</form>
add multiple functions to "onchange"
<form id="frm1" method="post">
<p>
<div>
<label>Board type:</label>
<!--<input id="boardtype" list="boards">-->
<!-- add JS functions separated by a semi-colon
The second function only works if the element
'vol' is empty-->
<select id="boards"
onchange="myFunction();if(document.getElementById('frm1').elements['vol'].value != ''){
myFormFunction()};">
<option value="OP1">selection1</option>
<option value="OP2">selection2</option>
</select>
</div>
<!-- snipped -->
fieldset forms using bootstrap
<!-- snipped -->
<!-- entry for one field -->
<fieldset class="form-group">
<label for="id_thickness">Thickness:</label>
<input class="form-control"
id="thick"
style="width: 300px;"
type="text"
maxlength="100"
placeholder="Enter width"
onchange="myFunction();
if(document.getElementById('frm1').elements['vol'].value != ''){
myFormFunction()};"/>
<small class="text-muted">
Example : 2 or 2 1/4
</small>
</fieldset>
Create form group as a grid using bootstrap
- http://v4-alpha.getbootstrap.com/components/forms/
- http://stackoverflow.com/questions/23530064/how-to-make-label-and-input-appear-on-the-same-line-in-html-form
- http://stackoverflow.com/questions/9737394/html-how-to-center-align-a-form
<div class="form-group row" align="center">
<label class="col-sm-2 form-control-label">Length:</label>
<div class="col-sm-10">
<input class="form-control"
id="len"
style="width: 300px;"
type="text"
maxlength="100"
placeholder="Enter length"
onchange="myFunction();
if(document.getElementById('frm1').elements['vol'].value != ''){
myFormFunction()};"/>
<small class="text-muted">
Example: 6 or 6 5
</small>
</div>
</div>