JavaScript also makes it possible to communicate with a server through technologies often referred as AJAX, whereby information is sent asynchronously to the server, and then processed accordingly.
<HEAD> tag includes information that will not be displayed on the page; for example, the title of the page, JavaScript code, or styling preferences.
CTRL + R refreshes a webpage.
It is good practice to add spaces around the operators such as +, -, /, or % for clarity. A block of instructions start with an opening curly bracket and that ends with a closing curly bracket.
---------------------------
/*Adding the following javascript code in the webpage will cause the url change to http://127.0.0.1:11760/Ireland and the page doesn't load.*/
<SCRIPT>
var name="Pat", location = "Ireland", year = 2018;
console.log(year);
</SCRIPT>
-------------------
var str1 = "string01";
var str2 = "string02";
var num1 = 1;
var strs_combined = str1 +str2;
var str_combine_num = str1 + num1;
alert(strs_combined);
alert(str_combine_num);
------------------
& can not be used in variable name.
---------------
var nameOfUser = prompt("Please enter your name","");
if (nameOfUser == "Patrick")
alert ("Hello Patrick");
else
alert ("Hello Stranger");
-------------------
var result = prompt("What is 1 + 1","");
resultAsNumber = parseInt(result);
if (resultAsNumber === 2)
alert ("Well done");
else
alert ("Sorry, wrong answer");
----------------------
A function can be called using the () operator
---------------
Global variables need to be declared at the start of the script (using the usual declaration syntax) and outside of any function. They can then be used anywhere in the script.
---------------
//If a variable is initialized in a method without being declared, it is considered as a global variable
function function3()
{
testGlobal = 3;
}
function3();
alert("value of testGlobal is: " + testGlobal);//this should display "value of test is: 3";
---------------
In JavaScript, a script will be executed until an error occurs in this script. When an error is detected, the browser will just stop to execute any further code.
--------------
<script type="text/javascript" src="myScript.js"></script>
<!-- linking to an external javascript file.-->
-----------------
We all learn by trial and error, and making mistakes is part of the learning process.
--------------
So, as you create your first script, set any fear aside, try to experiment, be curious, and get to learn the language. It is like learning a new foreign language: when someone from a foreign country understands your first sentences, you feel so empowered!
-----------------
Strings are considered as objects with associated attributes (often called properties) and functions (often referred as methods).
------------------
var myName = "Patrick";
var numberOfLetters = myName.length;
console.log("There are " + numberOfLetters + " letters in " +myName);
--------------------
var mySentence = "This is a short sentence.";
if (mySentence.indexOf("short") >=0 ) console.log ("Index of the word 'short' is: " + mySentence.indexOf("short"));
else
console.log ("'short' is not included in the sentence");
----------------
//slicing a string.
var mySentence = "This sentence is long and needs to be shorter";
var shorterSentence = mySentence.slice (0,14);
console.log(shorterSentence);
-----------------
var mySentence = "This sentence is long and needs to be shorter";
console.log(mySentence);
var modifiedSentence = mySentence.replace ("is long","is way too long");
console.log(modifiedSentence);
var upperCaseSentence = mySentence.toUpperCase();
console.log(upperCaseSentence);
var lowerCaseSentence = mySentence.toLowerCase();
console.log(lowerCaseSentence);
-------------------
var randomNmber = Math.random();
if (randomNmber <.7)
console.log ("there was a 70% chance for this message to be displayed");
else
console.log ("there was a 30% chance for this message to be displayed");
--------------------
var answer = prompt("Please enter your choice 1- 3","");
var choice = Number(answer);
switch (choice){
case 1:
console.log ("you chose 1");
break;
case 2:
console.log ("you chose 2");
break;
case 3:
console.log ("you chose 3");
break;
default:
console.log ("Default option");
break;
}
console.log ("We have exited the switch structure");
---------------
do
{
var answer = prompt("Please enter your choice 1- 3","");
var choice = Number(answer);
} while (choice <= 1 || choice >=3);
--------------------
var questions = ["What is 2+2", "What is 4+2", "What is 4+5"];
var correctAnswers = [4, 6, 9];
var score = 0;
for (i = 0; i < 3; i ++)
{
var answer = Number(prompt("Question "+ (i+1)+": "+questions[i],""));
if (answer == correctAnswers[i]) {
alert("Well done!");
score++;
}
else
alert ("Sorry wrong answer");
}
alert ("You answered " + score + " questions correctly");
---------------------
//creating an array
var words = new Array();
words[0] = "beauty";
words[1] = "peace";
words[2] = "calm";
console.log(words);
--------------------
var test = ["Noemy", "Alan", "John"];
console.log("Elements before sorting: " + test);
test.sort();
console.log("Elements after sorting: " + test);
-------------
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>My First HTML Page</TITLE>
<SCRIPT>
function updateTimer()
{
var todaysDate = new Date();
var enDate = new Date (2019, 2, 6, 23,59,59,0);
var diff = Math.abs(enDate-todaysDate);
var nbDays = Math.floor(diff/(1000*60*60*24));
var nbHours = Math.floor((diff%(1000*60*60*24))/(1000*60*60));
var nbMinutes = Math.floor((diff%(1000*60*60))/(1000*60));
var nbSeconds = Math.floor((diff%(1000*60))/(1000));
document.getElementById("timer").innerHTML = nbDays+" Days";
document.getElementById("timer").innerHTML += nbHours+" Hours";
document.getElementById("timer").innerHTML += nbMinutes+" Minutes";
document.getElementById("timer").innerHTML += nbSeconds+" Seconds";
}
</SCRIPT>
</HEAD>
<BODY onload="setInterval(updateTimer,1000);">
<DIV id = "timer"> </DIV>
</BODY>
</HTML>
-----------------------------
var student1 = {
fName: "Paul",
lName: "Murphy",
studentID:"ID101",
classes: ['CS700', 'CS800'],
displayName : function (){return "My name is " + this.fName + " "+this.lName;}
}
console.log(student1.displayName());
------------------
var student1 = {
fName: "Paul",
lName: "Murphy",
studentID:"ID101",
classes: ['CS700', 'CS800'],
displayName : function (){console.log("My name is " + this.fName + " "+this.lName);}
}
student1.displayName();
---------------
//adding new property to an exiting object
function Student (firstName, lastName, studendIdentification, classesAttended)
{
this.fName = firstName;
this.lName = lastName;
this.studentId = studendIdentification;
this.classes = classesAttended;
}
var student3 = new Student("David", "Callagher", "120",['CS700', 'CS800']);
console.log("Student3 " + student3.lName);
console.log("Student3 " + student3.classes[0]);
var student4 = new Student("Mary", "Black", "121",['CS701', 'CS800']);
console.log("Student4 " + student4.lName);
console.log("Student4 " + student4.classes[0]);
student3.fullName = student3.fName + " " + student3.lName;
console.log("Student 3's full name: "+student3.fullName);
---------------
function Student (firstName, lastName, studendIdentification, classesAttended)
{
this.fName = firstName;
this.lName = lastName;
this.studentId = studendIdentification;
this.classes = classesAttended;
this.fullName = this.fName + " " + this.lName;
this.nbModulesAttended = function() {return this.classes.length;}
}
var student3 = new Student("David", "Callagher", "120",['CS700', 'CS800']);
console.log("Student3 " + student3.lName);
console.log("Student3 " + student3.classes[0]);
var student4 = new Student("Mary", "Black", "121",['CS701', 'CS800']);
console.log("Student4 " + student4.lName);
console.log("Student4 " + student4.classes[0]);
console.log("Student 3's full name: "+student3.fullName);
console.log(student4.fullName);
console.log("Number of classes attended by Student 3: "+ student3.nbModulesAttended());
console.log(student4["fName"]);
--------------
console.log(Math.ceil(2.1));//3
----------------
var questions = ["electricity", "DNA"];
var answers = ["scientist1", "scientist2"];
var score = 0;
for (var i = 0; i < answers.length; i++)
{
var userAnswer = prompt ("Who discovered "+questions[i],"");
userAnswer = userAnswer.toLowerCase();
if (userAnswer == answers [i]) score++;
}
alert ("You have answered "+ score + " Questions correctly!");
--------------
<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT>
function readField ()
{
var text = document.getElementById("myText").innerHTML;
console.log("Text found: "+ text);
document.getElementById("myText").innerHTML = "Hello Stranger";
}
function checkField()
{
var fieldContent = document.getElementById("fName").value;
if (fieldContent == "") alert ("Sorry, this field should not be empty");
document.getElementById("fName").style.backgroundColor = "red";
}
</SCRIPT>
</HEAD>
<BODY >
<DIV onclick = "readField()" id = "myText"> Hello World</DIV>
First Name: <INPUT type = text id = "fName" onblur = "checkField()">
</BODY>
</HTML>
-----------------
<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT>
function copyAddress()
{
document.getElementById("b_fname").value = document.getElementById("s_fname").value;
document.getElementById("b_lname").value = document.getElementById("s_lname").value;
document.getElementById("b_address").value = document.getElementById("s_address").value;
}
</SCRIPT>
</HEAD>
<BODY >
<FORM>
Shipping Address<BR>
<TABLE border = 0>
<TR> <TD>First Name</TD><TD><INPUT id = "s_fname"> </TD> </TR>
<TR> <TD>Last Name</TD><TD><INPUT id = "s_lname"> </TD> </TR>
<TR> <TD>Shipping Address</TD><TD><INPUT id = "s_address"> </TD> </TR>
</TABLE>
<BR>
<BUTTON type = "button" onclick = "copyAddress();"> Same Shipping Details </BUTTON>
<BR>
<BR>
Billing Address<BR>
<TABLE border = 0>
<TR> <TD>First Name</TD><TD><INPUT id = "b_fname"> </TD> </TR>
<TR> <TD>Last Name</TD><TD><INPUT id = "b_lname"> </TD> </TR>
<TR> <TD>Shipping Address</TD><TD><INPUT id = "b_address"> </TD> </TR>
</TABLE>
</FORM>
</BODY>
</HTML>
--------------------
<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT>
function checkField()
{
var fieldToValidate = document.getElementById("phoneNumber");
var feedback = document.getElementById("feedback");
if (!fieldToValidate.checkValidity()) feedback.innerHTML = fieldToValidate.validationMessage;
}
</SCRIPT>
</HEAD>
<BODY >
<FORM>
Phone Number: <INPUT type = "number" id = "phoneNumber" onblur = "checkField()">
<DIV id="feedback"></DIV>
</FORM>
</BODY>
</HTML>
--------------------------
<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT>
function checkField()
{
var fieldToValidate = document.getElementById("phoneNumber");
var feedback = document.getElementById("feedback");
if (fieldToValidate.validity.valueMissing) feedback.innerHTML = "This field can't be left empty. Please enter a value";
}
</SCRIPT>
</HEAD>
<BODY >
<FORM>
Phone Number: <INPUT type = "number" id = "phoneNumber" onblur = "checkField()" required>
<DIV id="feedback"></DIV>
</FORM>
</BODY>
</HTML>
----------------------
<!DOCTYPE html>
<!--add event listner-->
<HTML>
<HEAD>
<SCRIPT>
function initEvents(){
document.getElementById("button").addEventListener ("click", displayMessage)
document.getElementById("button").addEventListener ("mouseover", displayMessageWhenOver);
}
function displayMessage()
{
console.log("You just clicked the button");
document.getElementById("button").removeEventListener ("mouseover", displayMessageWhenOver);
}
function displayMessageWhenOver()
{
console.log("You just moved the mouse over the button");
}
</SCRIPT>
</HEAD>
<BODY onload = "initEvents()">
<BUTTON id = "button" type = "button" > Click me </BUTTON>
</BODY>
</HTML>
---------------
In JavaScript terms, when we deal with the innermost element (i.e., the child), we say that we are bubbling events, and if we decide to deal with the outermost element (i.e., the parent), we say that we are capturing events.
By default, if you add an event to an element, events are bubbled; however, it is possible to modify this options when adding an event, by specifying a third attribute and setting it to true (for a capturing behavior).
---------------
<!DOCTYPE html>
<!--bubbling events-->
<HTML>
<HEAD>
<SCRIPT>
function initEvents() {
document.getElementById("table").addEventListener("click",displayMessageWhenTableClicked,flase);
document.getElementById("innerCell").addEventListener ("click", displayMessageWhenInnerCellClicked, flase);
}
function displayMessageWhenTableClicked()
{
console.log("You clicked within the table");
}
function displayMessageWhenInnerCellClicked()
{
console.log("You clicked within the cell");
}
</SCRIPT>
</HEAD>
<BODY onload="initEvents()">
<TABLE id = "table" style = "background-color: black">
<TR><TD>Inside TR</TD><TD>Inside TR</TD><TD>Inside TR</TD></TR>
<TR><TD>Inside TR</TD><TD id = "innerCell" style = "background-color: red">Click Me, I Am inside</TD><TD>Inside TR</TD></TR>
<TR><TD>Inside TR</TD><TD>Inside TR</TD><TD>Inside TR</TD></TR>
</TABLE>
</BODY>
</HTML>
-----------------------
<!DOCTYPE html>
<!--navigating through nodes-->
<HTML>
<HEAD>
<SCRIPT>
function countElements()
{
var body = document.getElementsByTagName("BODY")[0];
var parentOfBody = body.parentNode.nodeName;
console.log("Parent of BODY is "+parentOfBody);
var firstChild = body.firstChild.nodeName;
console.log("First Child of BODY is"+firstChild);
var lastChild = body.lastChild.nodeName;
console.log("Last Child of BODY is "+lastChild);
var nextSiblingOfId1 = document.getElementById("div1").nextSibling.nodeName;
console.log("The next sibling of DIV1 is "+nextSiblingOfId1);
}
</SCRIPT>
</HEAD>
<BODY onload = countElements()><DIV id = "div1"> Hello World 1</DIV><DIV id = "div2"> Hello World 2</DIV>
</BODY>
</HTML>
---------------------
<!DOCTYPE html>
<!--adding and removing nodes and elements-->
<HTML>
<HEAD>
<SCRIPT>
function modifyDocument(){
var newParagraph = document.createElement("p");
var nodeWithinParagraphElement = document.createTextNode("This is a new paragraph");
newParagraph.appendChild(nodeWithinParagraphElement);
document.getElementById("div1").appendChild(newParagraph);
var newParagraph2 = document.createElement("P");
var nodeWithinParagraphElement2 = document.createTextNode("This is a new paragraph that will appear before the previous one");newParagraph2.appendChild(nodeWithinParagraphElement2);
document.getElementById("div1").insertBefore(nodeWithinParagraphElement2, newParagraph);
}
function removeNodes()
{
var firstDiv = document.getElementById("div1");
if (firstDiv.firstChild) firstDiv.removeChild(firstDiv.firstChild);
}
</SCRIPT>
</HEAD>
<!--<BODY onload = countElements()><DIV id = "div1"> Hello World 1</DIV><DIV id = "div2"> Hello World 2</DIV>-->
<BODY onload = modifyDocument()><DIV id = "div1"> Hello World 1</DIV><DIV id = "div2"> Hello World 2</DIV>
<BUTTON onclick = "removeNodes()" type = button> Click here to remove paragraphs.</BUTTON>
</BODY>
</HTML>
-----------
<!DOCTYPE html>
<!--opening, closing and moving windows using javascript-->
<HTML>
<HEAD>
<SCRIPT>
function openWindow()
{
myWindow = window.open("","hello","menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes, width=300, height = 300");
}
function closeWindow()
{
myWindow.close();
}
function moveWindowRight()
{
myWindow.moveBy(100,0);
myWindow.focus();
}
function moveWindowLeft()
{
myWindow.moveBy(-100,0);
myWindow.focus();
}
function resizeWindow()
{
// myWindow.resizeTo(500, 500);
myWindow.resizeBy(-100,-100);
myWindow.focus();
}
</SCRIPT>
</HEAD>
<BODY>
<BUTTON onclick = "openWindow()" type = "button">Click to open a new window</BUTTON>
<BUTTON onclick = "closeWindow()" type = "button">Click to close the new window</BUTTON>
<BUTTON onclick = "moveWindowRight()" type = "button">Click to move new window to the right</BUTTON>
<BUTTON onclick = "moveWindowLeft()" type = "button">Click to move new window to the left</BUTTON>
<BUTTON onclick = "resizeWindow()" type = "button">Click to Resize the new window</BUTTON>
</BODY>
</HTML>
----------------
<!DOCTYPE html>
<!--working with browser's location-->
<HTML>
<HEAD>
<SCRIPT>
// specify that the function changeLocation should be called after 1 second (i.e., 1000 milliseconds).
// setInterval(changeLocation, 1000);
function changeLocation()
{
window.location.assign("http://www.baidu.com");
}
</SCRIPT>
</HEAD>
<BODY >
<BUTTON onclick = "changeLocation()" type = "button">Click to open go to Apple.com</BUTTON>
</BODY>
</HTML>
--------------------
<HTML>
<HEAD>
<SCRIPT>
var nbFields = 0;
function deleteTextFields()
{
var myNode = document.getElementById("div1");
var nbChild = myNode.childNodes.length;
console.log ("NB Children" + nbChild);
document.getElementById("div1").removeChild(myNode.childNodes[nbChild -1]);
document.getElementById("div1").removeChild(myNode.childNodes[nbChild -2]);
document.getElementById("div1").removeChild(myNode.childNodes[nbChild -3]);
nbFields--;
}
function addTextFields()
{
nbFields++;
var newParagraph = document.createElement("INPUT");
var label = document.createTextNode("Field" + nbFields);
var br = document.createElement("BR");
newParagraph.type = "text";
document.getElementById("div1").appendChild(label);
document.getElementById("div1").appendChild(newParagraph);
document.getElementById("div1").appendChild(br);
}
</SCRIPT>
</HEAD>
<BODY ><DIV id = "div1"></DIV>
<BUTTON onclick = "addTextFields()" type = button> Click here to add text fields</BUTTON>
<BUTTON onclick = "deleteTextFields()" type = button> Click here to delete text fields</BUTTON>
</BODY>
<HTML>