HTML, CSS and JavaScript


TheFrontEnd


VIEW SOURCE CODE BACK TO CATEGORIES







Up down arrow


HTML Code

HTML, CSS and JavaScript


Here you will find source code Snippets of HTML, CSS amd JavaScript. I'll be updating any necessary content delivery networks (CDM's) periodically as to stay up to date with the latest versions/releases. I'll be covering certain frameworks when I have the time including React, Angular, NodeJS and AJAX.

If you have any questions or suggestions send me a message.

Remember, to force a browser cache refresh and reload any page press Ctrl + F5. Or hold down Shift + Reload .

divider
1.0 Display Highlighted CSS On A WebPage

This first snippet is simply showing a way in which you can add highlighted source code as text to a website. The below example is for CSS but you can add just about any language. For a full list of the documentation and supported languages, visit the site Prism.

    
.all-backgrounds {

background: linear-gradient(rgba(0, 0, 0, 0.45), rgba(0, 0, 0, 0.45)), url(../static/backgrounds/../static/backgrounds/two.jpg) no-repeat center center;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
height: 100%;
overflow: auto;
}
    

As you can see if you view the source, all you need to do is enclose the CSS you want displayed with the below tagging.

<code>class="language-<whatever language"></code>
    
<pre>
    <code class="language-css">
        ...
    </code>
</pre>
    
1.1 Display Highlighted HTML On A WebPage

This snippet uses Prism like above but to display HTML, not CSS. It works the exact same way except you must escape certain characters when the HTML parsed. For example, you need to escape all < and > brackets that you find on 'link' and 'script' tags in order for Prism to display the HTML correctly on your page.

Firstly, head over to FreeFormatter and paste the HTML you want to display on your site into the text field and generate the markup. Then simply paste it into your text-editor or IDE with the following tags. Notice the different class name.

    
<pre>
    <code class="language-markup">
        ...
    </code>
</pre>
    
2.0 Bootstrap Price List Table

A simple Bootstrap pricing table.

    
<div class="row">
	<div class="col-md-10 offset-md-1">
		<form action="#" method="POST">
			<!-- ADDED FORM -->
			<table class="table table-striped table-bordered table-hover">
				<!-- 'table-dark' for dark -->
				<thead class="text-center">
					<tr>
						<th class="table-success">
							<h4>Free Plan</h4>
						</th>
						<th class="table-info">
							<h4>Standard Plan</h4>
						</th>
						<th class="table-danger">
							<h4>Premium Plan</h4>
						</th>
					</tr>
				</thead>
				<tbody>

					<tr class="text-center">
						<td>
							<h3>$ 0</h3>
						</td>
						<td>
							<h3>$ 99</h3>
						</td>
						<td>
							<h3>$ 999</h3>
						</td>
					</tr>
					<tr class="text-center">
						<td>Lorem ipsum</td>
						<td>Lorem ipsum</td>
						<td>Lorem ipsum</td>
					</tr>
					<tr class="text-center">
						<td>Lorem ipsum</td>
						<td>Lorem ipsum</td>
						<td>Lorem ipsum</td>
					</tr>
					<tr class="text-center">
						<td>Dolor sit amet</td>
						<td>Lorem ipsum</td>
						<td>Lorem ipsum</td>
					</tr>
					<tr class="text-center">
						<td>-</td>
						<td>Dolor sit amet</td>
						<td>Lorem ipsum</td>
					</tr>
					<tr class="text-center">
						<td>-</td>
						<td>-</td>
						<td>Lorem ipsum</td>
					</tr>
					<tr class="text-center">
						<td><a href="#"><button type="submit" name="but1" class="btn btn-success btn-block">Purchase</button></a></td>
						<td><a href="#"><button type="submit" name="but2" class="btn btn-info btn-block">Purchase</button></a></td>
						<td><a href="#"><button type="submit" name="but3" class="btn btn-danger btn-block">Purchase</button></a></td>
					</tr>
				</tbody>
			</table>
		</form>
	</div>
</div>

    
Price Table
3.0 JavaScript

Comparison difference between == and ===

    
var aNumber = 10;
var aString = "10";

document.write(typeof(aNumber));
document.write("
"); document.write(typeof(aString)); document.write("
"); //Will return true because the actual values are the same. ' == ' ignores type comparison document.write(aNumber == aString); document.write("
"); //Will return false because the actual values are the same BUT ' === ' also compares the data types which are NOT the same document.write(aNumber === aString);
3.1 JavaScript Objects

An object is defined with curly brackets and information is stored in typical key/value pairs.

    
//A JavaScript Object - Key value pairs
var myObject = 	{
  "firstName": "Humpty",
  "lastName": "Dumpty",
  "dateOfBirth": 1901,
  "phone": 0414098432,
  "country": "Australia"
}

//To access a specific value use its corresponding key along with the dot (.) notation.
//Get the last name value
var getLastName = myObject.lastName;
console.log("LastName: " +getLastName+ "\n");

//Get the phone number value
var getPhone = myObject.phone;
console.log("Phone Number: " +getPhone+ "\n");

//You can also get a value using the square brackets
var getCountry = myObject["country"];
console.log("Country: " +getCountry+ "\n");

//If you want to get ALL the KEYS in the object use a "for in" loop
console.log("Key Names:::::: ");
for (key in myObject)	{
  console.log(key);
}

console.log("\n");

//If you want to get ALL the VALUES in the object also use a "for in" loop
console.log("Values:::::: ");
for (value in myObject)	{
console.log(myObject[value]);
}

console.log("\n");

//Another way to get ALL the Values is to use the Object.values(yourObject)
//This will return an array of values, not strings like above
console.log(Object.values(myObject));

console.log("\n");

//Print all keys and values together
console.log("Console all key value pairs:::::");
for (pair in myObject)	{
	console.log("Key = "+pair+ ", Value =  " +myObject[pair]);
}

3.1 Output
	
"LastName: Dumpty
"
"Phone Number: 414098432
"
"Country: Australia
"
"Key Names:::::: "
"firstName"
"lastName"
"dateOfBirth"
"phone"
"country"
"
"
"Values:::::: "
"Humpty"
"Dumpty"
1901
414098432
"Australia"
"
"
["Humpty", "Dumpty", 1901, 414098432, "Australia"]
"
"
"Console all key value pairs:::::"
"Key = firstName, Value =  Humpty"
"Key = lastName, Value =  Dumpty"
"Key = dateOfBirth, Value =  1901"
"Key = phone, Value =  414098432"
"Key = country, Value =  Australia"
    
4.0 Array of Objects

How an array of objects is implemented in JavaScript.

    
//A JavaScript arrray of objects
var myObjectArray =
[
  {
    "carMake": "Porsche",
    "carModel": "928",
    "carColour": "black",
    "automatic": false,
    "topSpeed": 280
  },
  {
    "carMake": "Ferrari",
    "carModel": "F-50",
    "carColour": "red",
    "automatic": false,
    "topSpeed": 330
  },
  {
    "carMake": "Lamborghini",
    "carModel": "Centenario",
    "carColour": "grey",
    "automatic": false,
    "topSpeed": 350
  },
  {
    "carMake": "Bugatti",
    "carModel": "Chiron",
    "carColour": "blue",
    "automatic": true,
    "topSpeed": 415
  }
]

//Get a single value top speed value from Lamborghini item
let getTopSpeed = myObjectArray[2].topSpeed;
console.log(getTopSpeed);

//Could also do this to get a single item. Returns an array
console.log(Object.entries(myObjectArray[1])[4]);

//Get all Models names from ALL items
for (i in myObjectArray){
  let getModelNames = myObjectArray[i].carModel;
  console.log("Model name: "+getModelNames);
}

//Get all key names only
console.log(Object.entries(myObjectArray));

//Get ALL key names and values
for (j in myObjectArray){
  let getKeyandValue = myObjectArray[j];
  console.log(getKeyandValue);
}

//If you want to return an array of all key and value pairs. Array of arrays
console.log(Object.entries(myObjectArray[1]));

    
4.0 Output
	
350
["topSpeed", 330]
"Model name: 928"
"Model name: F-50"
"Model name: Centenario"
"Model name: Chiron"
[["0", [object Object] {
  automatic: false,
  carColour: "black",
  carMake: "Porsche",
  carModel: "928",
  topSpeed: 280
}], ["1", [object Object] {
  automatic: false,
  carColour: "red",
  carMake: "Ferrari",
  carModel: "F-50",
  topSpeed: 330
}], ["2", [object Object] {
  automatic: false,
  carColour: "grey",
  carMake: "Lamborghini",
  carModel: "Centenario",
  topSpeed: 350
}], ["3", [object Object] {
  automatic: true,
  carColour: "blue",
  carMake: "Bugatti",
  carModel: "Chiron",
  topSpeed: 415
}]]
[object Object] {
  automatic: false,
  carColour: "black",
  carMake: "Porsche",
  carModel: "928",
  topSpeed: 280
}
[object Object] {
  automatic: false,
  carColour: "red",
  carMake: "Ferrari",
  carModel: "F-50",
  topSpeed: 330
}
[object Object] {
  automatic: false,
  carColour: "grey",
  carMake: "Lamborghini",
  carModel: "Centenario",
  topSpeed: 350
}
[object Object] {
  automatic: true,
  carColour: "blue",
  carMake: "Bugatti",
  carModel: "Chiron",
  topSpeed: 415
}
[["carMake", "Ferrari"], ["carModel", "F-50"], ["carColour", "red"], ["automatic", false], ["topSpeed", 330]]
	
5.0 Simple Login Authorization

A couple ways to implement a simple login to check email and username. In the real world of course a database would be storing the user values but in these simple examples, an array of objects has been used to represent the database.

    
var users =
    [
        {
            "email": "leo@hot.com",
            "password": "poo",
            "name": "Leon"
        },
        {
            "email": "leon@hot.com",
            "password": "poop",
            "name": "Mark"
        },
        {
            "email": "lee@hot.com",
            "password": "foot",
            "name": "Pissant"
        },
        {
            "email": "joanne@hot.com",
            "password": "jo1",
            "name": "Joanne"
        }
    ];  
//Simple email and password check
let checkUser = function (email, password, allUsers) {

    var stringTemplate = `Congrats you are in `;
    var user;

    for (user in allUsers) {
        //Can also use allUsers[user]['email'] && allUsers[user]['password'] here
        //Just remember the first square brackets refers to the index of any one whole object,
        //and the second brackets refers to the index of the value of in a specific object
        if (email === allUsers[user].email && password === allUsers[user].password) {
            return stringTemplate + allUsers[user].name;
        }
    }
    return "HACKER DETECTED!";
};

let authorise = checkUser("lee@hot.com", "foot", users);
console.log(authorise);

//Another way to check for username and password separately
let checkUser2 = function (email, password, allUsers) {
    var isUsedrnameGood = false;
    var isPasswordGood = false;
    var user;
    var getName = "";

    for (user in users) {
        if (email === allUsers[user]['email']) {
            if (password === allUsers[user]['password']) {
                isUsedrnameGood = true;
                isPasswordGood = true;
                getName = users[user]['name'];
                break
            }
            else {
                isUsedrnameGood = true;
                isUsedrnameGood = false;
                break
            }
        }
        isUsedrnameGood = false;
    }

    if (isUsedrnameGood === true && isPasswordGood === true) {
        console.log(`Welcome ${getName}, you are granted access`);
    }
    else if (isUsedrnameGood === true && isPasswordGood === false) {
        console.log(`Sorry ${getName}, your password is incorrect. Try again`);
    }
    else {
        console.log(`Sorry ${getName}, both your username and password are incorrect`);
    }
};

checkUser2("joanne@hot.com", "jo1", users);

    
5.0 Output
	
Congrats you are in Pissant
Welcome Joanne, you are granted access
	
6.0 String, Number and array JavaScript fucntions

Here you will find a list of JavaScript built in functions for Strings, Numbers and arrays. There are many more but I have listed the ones in which I beleive are important.

    
//STRINGS - Built in functions (Remember Strings are immutable)
var name = "The cat sat on the mat";

//Simply returns the string length, or the number of characters, including spaces.
console.log(name.length);

//Count from the first letter beginning at zero until you reach the 4th letter, that character is returned.
console.log(name.charAt(4));

//Count from the first letter beginning at zero until you reach the letter 't', that index number value is returned.
console.log(name.indexOf('t'));

//First argument is the index of first character, second is the length of the substring, counting zero from index 4.
console.log(name.substr(4, 3));

//Similar to above function but the second argument counts from the beginning of the string, NOT from index 8.
console.log(name.slice(8, 11));

//First argument is the substring to be replaced, second argument is the new string that will be used.
console.log(name.replace('cat', 'dog'));

//Simply concatenates the argument string to the end of the original string.
console.log(name.concat(" Whatever"));

//All uppercase
console.log(name.toUpperCase());

//All lower case
console.log(name.toLowerCase());

//Convert a String to an array. Breaks apart the string at all 'spaces'.
console.log(name.split(" "));

//NUMBERS - Built in functions

//Convert number to String (1st way)
var myNumber = 1234;
var convertToString = myNumber.toString();
console.log(typeof convertToString);

//Convert number to String (2nd way)
var convertToString2 = String(myNumber);
console.log(typeof convertToString2);

//Convert number to String (3rd way)
var convertToString3 = "" + myNumber;
console.log(typeof convertToString3);

//Simply returns the primitive value of a number. Think of a getter method.
console.log(myNumber.valueOf());

//Convert a variable to a Number
var stringNumber = "12";
console.log(Number(stringNumber));

//ARRAYS - Built in functions

//Convert an array to a String
var myArray = [9, 8, 7, 6, 5];
console.log(myArray);
var convertToString4 = myArray.toString();
console.log(typeof convertToString4);
console.log(convertToString4);

//If you want to check the data type for an array don't use 'typeof' which returns 'object', instead use Array.
//Returns true if its an array, false otherwise.
console.log(Array.isArray(myArray));

//Add an element to the END of an array
myArray.push(34);
console.log(myArray);

//Removes and returns the LAST element of an array
myArray.pop();
console.log(myArray);

//Add an element to the START of an array
myArray.unshift(56);
console.log(myArray);

//Remove and return the FIRST element of an array
myArray.shift();
console.log(myArray);

//INSERT an item at 1st index position
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

//REPLACE first item at the 4th index
months.splice(4, 1, 'May');
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']

//Remove an element at a specified index of an array
//NOTE - An empty spot remains in the array after deleting. It does not auto shift elements to remove the empty.
delete myArray[2];
console.log(myArray);

//Modify an item at a specific index of an array
myArray[2] = 100;
console.log(myArray);

//Combine, concatenate or merge two arrays
var firstArray = ["Hello", "There", "Bob"];
var secondArray = [1, 2, 4];
console.log(firstArray.concat(secondArray));


    
6.0 Output
	
22
c
6
cat
sat
The dog sat on the mat
The cat sat on the mat Whatever
THE CAT SAT ON THE MAT
the cat sat on the mat
[ 'The', 'cat', 'sat', 'on', 'the', 'mat' ]
string
string
string
1234
12
[ 9, 8, 7, 6, 5 ]
string
9,8,7,6,5
true
[ 9, 8, 7, 6, 5, 34 ]
[ 9, 8, 7, 6, 5 ]
[ 56, 9, 8, 7, 6, 5 ]
[ 9, 8, 7, 6, 5 ]
[ 'Jan', 'Feb', 'March', 'April', 'June' ]
[ 'Jan', 'Feb', 'March', 'April', 'May' ]
[ 9, 8, <1 empty item>, 6, 5 ]
[ 9, 8, 100, 6, 5 ]
[ 'Hello', 'There', 'Bob', 1, 2, 4 ]
	
7.0 JavaScripts Quirks

Odd behaviors to the JavaScript language.

    
//JavaScript operator Quirks - TYPE COERCION (just be careful when using operators on Stings and Numbers
//A string number subtracted or multiplied by a Number will yield a Number result
var myStringNumber = "10";
var myNumber = 5;
var result1 = myStringNumber - myNumber;
console.log(`"10" - 5 = ${result1}`);
console.log("String number subtracted with an integer value results in a type: " +typeof result1);

var result2 = myStringNumber * myNumber;
console.log(`"10" * 5 = ${result2}`);
console.log("String number multiplied with an integer value results in a type: " +typeof result2);

//A string number added to a number results in a String type (concatenation)
var result3 = "25 " + 10;
console.log(`"25" + 10 = ${result3}`);
console.log("String number added with an integer value results in a type: " +typeof result3);

//Simple ternary operator
var getTernary = 100 < 50 ? "100 IS greater than 50" : "100 is NOT greater than 50";
console.log(getTernary);
    
7.0 Output
	
"10" - 5 = 5
String number subtracted with an integer value results in a type: number
"10" * 5 = 50
String number multiplied with an integer value results in a type: number
"25" + 10 = 25 10
String number added with an integer value results in a type: string
100 is NOT greater than 50
	
Up Arrow