Saturday, July 3, 2021

Head First HTML5 Programming - Day 1 - 07/03/2021

How to convert old HTML to HTML5?

1. Following is HTML4.0 DocType

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Head First Lounge</title>
<link type="text/css" rel="stylesheet" href="lounge.css">
<script type="text/javascript" src="lounge.js"></script>
</head>
<body>
<h1>Welcome to Head First Lounge</h1>
<p>
<img src="drinks.gif" alt="Drinks">
</p>
<p>
Join us any evening for refreshing <a href="elixirs.html">elixirs</a>,
conversation and maybe a game or two of Tap Tap Revolution.
Wireless access is always provided; BYOWS (Bring Your Own Web Server).
</p>
</body>
</html>

If you look at the markup highlighted in orange - it belongs to HTML 4.0. This doctype tell the browser the type of document it is.

And HTML5 doc type is as below
<!doctype html>

It's not only for HTML5 - but for all future versions of it.

2. Following is an example of Meta Tag of HTML4 vs HTML5

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<meta charset="utf-8">

3. Link attribute. - HTML4 vs HTML5

<link type="text/css" rel="stylesheet" href="lounge.css">

To upgrade this for HTML5, we just need to remove the type attribute. Why?
Because CSS has been declared the standard, and default, style for HTML5. So,
after we remove the type attribute, the new link looks like this:

<link rel="stylesheet" href="lounge.css">

4. Script Tag

With HTML5, JavaScript is now the standard and default scripting language, so you can
remove the type attribute from your script tags too. Here’s what the new
script tag looks like without the type attribute:
<script src="lounge.js"></script>
Or if you have some inline code, you can just write your script like this:
<script>
var youRock = true;
</script>
 

Exercise 1 - JS

var drink = "Energy Drink";
var lyrics = "";
var cans = 99;
while (cans > 0) {
lyrics = lyrics + cans + " cans of "
+ drink + " on the wall <br>";
lyrics = lyrics + cans + " cans of "
+ drink + "<br>";
lyrics = lyrics + "Take one down, pass it around,<br>";
if (cans > 1) {
lyrics = lyrics + (cans-1) + " cans of "
+ drink + " on the wall <br>";
}
else {
lyrics = lyrics + "No more cans of "
+ drink + " on the wall <br>";
}
cans = cans - 1;
}
document.write(lyrics);

Here, document.write will write actually into HTML page.

I get that we built up the entire lyrics to the
song, but what exactly did the document.write do
and how did the text get in the document?
A: Well, document.write takes a string of text and
inserts it into the document; in fact, it outputs the string
precisely where the script tag is located. So, in this
case document.write outputs the string right into the
body of the page.
You’re soon going to see more sophisticated ways to
alter the text of a live document with JavaScript, but
this example should give you a flavor of how code can
dynamically change a page.


Instead if I use console.log(lyrics) - it will write everything into console instead of html page.

JavaScript

alert("Mandar") -- this will open a alert message in browser.

You can add JavaScript in 3 ways into your html page
Place your script inline, in the <head> element.
The most common way to add code to your pages is to put a <script> element in the head of your page. When you add JavaScript in the <head> element, it is executed as soon as the browser parses the head (which it does first!), before it has parsed the rest of the page.

Add your script by referencing a separate JavaScript file.
You can also link to a separate file containing JavaScript code. Put the URL of the file in the src attribute of the opening <script> tag and make sure you close the script element with </script>. If you’re linking to a file in the same directory, you can just use the name of the file.


<head>
    <script>
        statement
    </script>
    <script src=”mycode.js”>
    </script>
</head>

<body>
    <script>
        statement
        statement
    </script>
</body>


Add your code in the body of the document, either inline or as a link to a separate file

Or, you can put your code right in the body of your HTML. Again, enclose your JavaScript code in the <script> element (or reference a separate file in the src attribute). JavaScript in the body of your
page is executed when the browser parses the body (which it does, typically, top down).

To interact with HTML DOM elements, you can use javascript's method getElementById("")
var planet = document.getElementById("greenplanet");

Here, document represent entire page of a browser and contains complete DOM, so we can ask to do things like find an element with specific id

planet.innerHTML = "Red Alert: hit by phaser fire!";

We can use innerHTML property of element to change the content of the element. 

Most of the time it makes sense to start executing your JavaScript code after the page is fully loaded. The reason? Well, if you don’t wait until the page has loaded, then the DOM won’t be fully created when your code executes. In our case, the JavaScript is executing when the browser first loads the head of the page, and before the rest of the page has loaded, and so the DOM hasn’t been fully created yet. And, if the DOM isn’t created, then the <p id="greenplanet"> element doesn’t exist yet!

So what happens? The call to get the element with an id of greenplanet isn’t going to return anything because there is no matching element, and so the browser just keeps moving on and renders the page anyway after your code has run. So you’ll see the page rendered, but the text in the green planet won’t be altered by the code.

What we need is a way to tell the browser “run my code after you’ve fully loaded in the page and created the DOM.”

To tell the browser to wait before executing code we are going to use following code

<script>
function init() {
var planet = document.getElementById("greenplanet");
planet.innerHTML = "Red Alert: hit by phaser fire!";
}
window.onload = init;
</script>

Get Elements from DOM
Of course you already know this because we’ve been using document.getElementById, but there are other ways to get elements as well; in fact, you can use tag names, class names and attributes to retrieve not just one element, but a whole set of elements (say all elements in the class “on_sale”). And you can get form values the user has typed in, like the text of an input element.

Create or add elements to the DOM.
You can create new elements and you can also add those elements to the DOM. Of course, any changes you make to the DOM will show up immediately as the DOM is rendered by the browser (which is a good thing!).

Remove elements from the DOM.
You can also remove elements from the DOM by taking a parent element and removing any of its children. Again, you’ll see the element removed in your browser window as soon as it is deleted from the DOM.


Get and set the attributes of elements
So far you’ve accessed only the text content of an element, but you can access attributes as well. For instance, you might want to know what an element’s class is, and then change the class it belongs to on the fly.

Property Vs Attribute
Attribute is something which you can initialize and change; however property you can not initialize or change.

Create a new HTML element
var li = document.createElement("li");

Add an attribute value to new element
li.innerHTML = songName;

To locally store elements in browser 

Keep following code in separate JS file e.g.store.js

function save(item) {
    var playlistArray = getStoreArray("playlist");
    playlistArray.push(item);
    localStorage.setItem("playlist", JSON.stringify(playlistArray));
}

function loadPlaylist() {
    var playlistArray = getSavedSongs();
    var ul = document.getElementById("playlist");
    if (playlistArray != null) {
        for (var i = 0; i < playlistArray.length; i++) {
            var li = document.createElement("li");
            li.innerHTML = playlistArray[i];
            ul.appendChild(li);
        }
    }
}

function getSavedSongs() {
    return getStoreArray("playlist");
}

function getStoreArray(key) {
    var playlistArray = localStorage.getItem(key);
    if (playlistArray == null || playlistArray == "”) {
        playlistArray = new Array();
    }
    else {
        playlistArray = JSON.parse(playlistArray);
    }
    return playlistArray;
}


add this store.js file in your main html file
<script src="store.js"></script>

Call function inside store.js as below

function init() {
    var button = document.getElementById("addButton");
    button.onclick = handleButtonClick;
    loadPlaylist();
}


function handleButtonClick() {
    var textInput = document.getElementById("songTextInput");
    var songName = textInput.value;
    var li = document.createElement("li");
    li.innerHTML = songName;
    var ul = document.getElementById("list");
    ul.appendChild(li);
    save(songName);
}

Parameter Vs Arguments
. When you define a function you can define it with one or more parameters
function cook(degrees, mode, duration) {
// your code here
}
. When you call a function, you call it with arguments:
cook(425.0, "bake", 45);

You define a function with parameters, you call a function with arguments

the variables you define outside a function are globally scoped, and the function variables are locally scoped

Globals live as long as the page. A global variable begins life when its JavaScript is loaded
into the page. But, your global variable’s life ends when the page goes away. Even if you reload the
same page, all your global variables are destroyed and then recreated in the newly loaded page.

Local variables typically disappear when your function ends. Local variables are created when your function is first called and live until the function returns (with a value or not). That said, you can take the values of your local variables and return them from the function before the variables meet their digital maker.

You “shadow” your global.
Here’s what that means: say you have a global variable beanCounter and you then declare a function, like this

var beanCounter = 10;
function getNumberOfItems(ordertype) {
var beanCounter = 0;
if (ordertype == "order") {
// do some stuff with beanCounter...
}
return beanCounter;
}

When you do this, any references to beanCounter within the function refer to the local variable and not the global. So we say the global variable is in the shadow of the local variable (in other words we can’t see it because the local version is in our way).

functions are also values

function addOne(num) {
return num + 1;
}
var plusOne = addOne;
var result = plusOne(1);

your function can be anonymous

function(num) {
    return num + 1;
}
var f = function(num) {
    return num + 1;
}
var result = f(1);
alert(result);

functions as values

So what’s the big deal? Why is this useful? Well, the important thing isn’t so much that we can assign a function to a variable, that’s just our way of showing you that a function actually is a value. And you know you can store values in variables or arrays, you can pass them as arguments to functions, or as we’ll soon see, you can assign them to the properties of objects. But, rather than talking you through how anonymous functions are useful, let’s just look at one of the many ways using functions as values starts to get interesting

function init() {
alert("you rule!");
}
window.onload = init;

or

window.onload = function() {
alert("you rule!");
}

How to create an object in JavaScript
So we’ve got a object with some properties; how do we create this using JavaScript? Here’s how:

var fido = {
name: "Fido",
weight: 40,
breed: "Mixed",
loves: ["walks", "fetching balls"]
};

Access objects properties
dot notation - fido.weight
[] notation - fido["weight"]


Change property values
fido.weight = 27;
fido.breed = "Chawalla/Great Dane mix";
fido.loves.push("chewing bones");

Enumerate all an object’s properties
var prop;
for (prop in fido) {
    alert("Fido has a " + prop + " property ");
    if (prop == "name") {
        alert("This is " + fido[prop]);
    }
}

object’s array
var likes = fido.loves;
var likesString = "Fido likes";
for (var i = 0; i < likes.length; i++) {
    likesString += " " + likes[i];
}
alert(likesString);

Pass an object to a function
function bark(dog) {
    if (dog.weight > 25) {
        alert("WOOF");
    } else {
        alert("yip");
    }
}

To add a property to an object
fido.age = 5

To delete a property to an object
delete fido.age


passing objects to functions
When an object is assigned to a variable, the variable is given a reference to the object. It doesn’t “hold” the object itself

So, when you call a function and pass it an object, you’re passing the object reference—not the object itself, just a “pointer” to it. A copy of the reference is passed into the parameter, which then points to the original object

So, what does this all mean? Well, when you change a property of the object, you’re changing the property in the original object, not a copy, and so, you’ll see all the changes you make to an object within and outside of your function

When an object has a function in it, we say that object has a method.
var fido = {
    name: "Fido",    
    weight: 40,
    breed: "Mixed",
    loves: ["walks", "fetching balls"]
    bark: function() {
        alert("Woof woof!");
    }
};

calling method of an object
fido.bark()


Make a constructor ()

function Dog(name, breed, weight) {
    this.name = name;
    this.breed = breed;
    this.weight = weight;
    this.bark = function() {
        if (this.weight > 25) {
            alert(this.name + " says Woof!");
            } else {
            alert(this.name + " says Yip!");
        }
    };
}

Calling constructor
var fido = new Dog("Fido", "Mixed", 38);
var tiny = new Dog("Tiny", "Chawalla", 8);
var clifford = new Dog("Clifford", "Bloodhound", 65);

window object
When you’re writing code for the browser, the window object is always going to be part of your life. The window object represents both the global environment for your JavaScript programs and the main window of your app, and as such, it contains many core properties and methods. Let’s take a look at it:

Window is the global object. 
It may seem a little weird, but the window object acts as your global environment, so the names of any
properties or methods from window are resolved even if you don’t prepend them with window.
In addition, any global variables you define are also put into the window namespace, so you can reference them as window.myvariable.

window -- Object
-- Object Properties
location
status
onload
document
-- Object Methods
alert
prompt
open
close
setTimeout
setInterval


document -- Object
-- Object Properties
domain
title
URL
-- Object Methods
getElementById
getElementsByTagName
getElementsByClassName
createElement



p --Object
-- Object Properties
innerHTML
childElementCount
firstChild
-- Object Methods
appendChild
insertBefore
setAttribute
getAttribute























No comments:

Post a Comment

All about CSS

From book HTML & CSS - Design and Build Websites - Jon Duckett CSS works by associating rules with HTML elements. These rules govern how...