This document provides an introduction and overview of JavaScript. It begins with an explanation of what dynamic HTML (DHTML) is and its key technologies including HTML, CSS, JavaScript, and the DOM. It then discusses what JavaScript is, its advantages, and what it can do. The document outlines how JavaScript code can be implemented in web pages and describes basic JavaScript syntax including variables, data types, operators, and conditional and loop statements. It provides examples of JavaScript functions, events, and interacting with HTML elements.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
2. Table of Contents
What is DHTML?
DHTMLTechnologies
HTML, CSS, JavaScript, DOM
2
3. Table of Contents (2)
Introduction to JavaScript
What is JavaScript
Implementing JavaScript into Web pages
In <head> part
In <body> part
In external .js file
3
4. Table of Contents (3)
JavaScript Syntax
JavaScript operators
JavaScript DataTypes
JavaScript Pop-up boxes
alert, confirm and prompt
Conditional and switch statements, loops and
functions
4
6. What is DHTML?
Dynamic HTML (DHTML)
Makes possible a Web page to react and change
in response to the user’s actions
DHTML = HTML + CSS + JavaScript
6
DHTML
HTML CSS JavaScript DOM
7. DTHML = HTML + CSS + JavaScript
HTML defines Web sites content through
semantic tags (headings, paragraphs, lists, …)
CSS defines 'rules' or 'styles' for presenting
every aspect of an HTML document
Font (family, size, color, weight, etc.)
Background (color, image, position, repeat)
Position and layout (of any object on the page)
JavaScript defines dynamic behavior
Programming logic for interaction with the user,
to handle events, etc. 7
9. JavaScript
JavaScript is a front-end scripting language
developed by Netscape for dynamic content
Lightweight, but with limited capabilities
Can be used as object-oriented language
Client-side technology
Embedded in your HTML page
Interpreted by theWeb browser
Simple and flexible
Powerful to manipulate the DOM 9
10. JavaScript Advantages
JavaScript allows interactivity such as:
Implementing form validation
React to user actions, e.g. handle keys
Changing an image on moving mouse over it
Sections of a page appearing and disappearing
Content loading and changing dynamically
Performing complex calculations
Custom HTML controls, e.g. scrollable table
Implementing AJAX functionality 10
11. What Can JavaScript Do?
Can handle events
Can read and write HTML elements and
modify the DOM tree
Can validate form data
Can access / modify browser cookies
Can be used as object-oriented language
Can handle exceptions
Can perform asynchronous server calls (AJAX)
11
12. JavaScript Output
12
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
Writing into an HTML element, using
innerHTML.
Writing into the HTML output using
document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using
console.log().
15. Using JavaScript Code
The JavaScript code can be placed in:
<script> tag in the head
<script> tag in the body – not recommended
External files, linked via <script> tag the head
Files usually have .js extension
Highly recommended
The .js files get cached by the browser
15
<script src="scripts.js" type="text/javscript">
<!– code placed here will not be executed! -->
</script>
16. JavaScript – When is Executed?
JavaScript code is executed during the page
loading or when the browser fires an event
All statements are executed at page loading
Some statements just define functions that can
be called later
Function calls or code can be attached as
"event handlers" via tag attributes
Executed when the event is fired by the browser
16
<img src="logo.gif" onclick="alert('clicked!')" />
17. <html>
<head>
<script type="text/javascript">
function test (message) {
alert(message); essa
}
</script>
</head>
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
Calling a JavaScript Function
from Event Handler – Example
image-onclick.html
17
18. Using External Script Files
Using external script files:
External JavaScript file:
18
<html>
<head>
<script src="sample.js" type="text/javascript">
</script>
</head>
<body>
<button onclick="sample()" value="Call JavaScript
function from sample.js" />
</body>
</html>
function sample() {
alert('Hello from sample.js!')
}
external-JavaScript.html
sample.js
The <script> tag is always empty.
20. JavaScript Syntax
The JavaScript syntax is similar to C# and Java
Operators (+, *, =, !=, &&, ++, …)
Variables (typeless)
Conditional statements (if, else)
Loops (for, while)
Arrays (my_array[]) and associative arrays
(my_array['abc'])
Functions (can return value)
Function variables
20
21. Variables
21
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names
(age, sum, totalVolume).
The general rules for constructing names for variables (unique
identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter
Names can also begin with $ and _ (but we will not use it in this tutorial)
Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as names
22. DataTypes
JavaScript data types:
Numbers (integer, floating-point)
Boolean (true / false)
String type – string of characters
Arrays
Associative arrays (hash tables)
22
var myName = "You can use both single or double
quotes for strings";
var my_array = [1, 5.3, "aaa"];
var my_hash = {a:2, b:3, c:"text"};
23. Greater than
<=
Symbol Meaning
>
< Less than
>= Greater than or equal to
Less than or equal to
== Equal
!= Not equal
Conditional Statement (if)
23
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}
24. Conditional Statement (if) (2)
Very often when you write code, you want to perform diff
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
24
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
The if Statement syntax
if (condition) {
block of code to be executed if the condition is true
}
25. 25
Conditional Statement (else,
else if)
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
The else Statement syntax
The else if Statement syntax
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
26. Switch Statement
The switch statement works like in C#:
26
switch (variable) {
case 1:
// do something
break;
case 'a':
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
switch-statements.html
27. Loops
Like in C#
for loop
while loop
do … while loop
27
var counter;
for (counter=0; counter<4; counter++) {
alert(counter);
}
while (counter < 5) {
alert(++counter);
} loops.html
35. 35
getElementById
Now we get the data from HTML elements by it’s id
For this purpose we using getElementById
Function
Like this:
document.getElementById(“ Id of HTML elements")
37. HTML Events
37
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can
"react" on these events.
An HTML event can be something the browser does, or
something a user does.
Here are some examples of HTML events:
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
Often, when events happen, you may want to do
something.
JavaScript lets you execute code when events are
detected.
38. 38
HTML allows event handler attributes, with JavaScript code,
to be added to HTML elements.
With single quotes:
<element event='some JavaScript‘>
With double quotes:
<element event="some JavaScript">
HTML Events..
<p>Click the button to display the date.</p>
<input type = “button” onclick="displayDate()“ value =“The time is?”>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
In the following example, an onclick attribute (with code), is added to
a <button> element:
39. Standard Popup Boxes
Alert box with text and [OK] button
Just a message shown in a dialog box:
Confirmation box
Contains text, [OK] button and [Cancel] button:
Prompt box
Contains text, input field with default value:
39
alert("Some text here");
confirm("Are you sure?”,”defaualt text”);
prompt ("enter amount", 10);
40. Sum of Numbers – Example
sum-of-numbers.html
40
<html>
<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 =
parseInt(document.mainForm.textBox1.value);
value2 =
parseInt(document.mainForm.textBox2.value);
sum = value1 + value2;
document.mainForm.textBoxSum.value = sum;
}
</script>
</head>
43. 43
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
JavaScript Confirm– Example
The window.confirm() method can be written without the window prefix.
Confirmation Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
var person = prompt("Please enter your name",
“Ahmad Mahmood");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?"; }
A prompt box is often used if you want the user to input a
value before entering a page.
When a prompt box pops up, the user will have to click
either "OK" or "Cancel" to proceed after entering an input
value.
If the user clicks "OK" the box returns the input value. If the
user clicks "Cancel" the box returns null.
44. Array
44
JavaScript arrays are used to store multiple values in a single
variable.
var cars = ["Saab", "Volvo", "BMW"];
Definition :
An array is a special variable, which can hold more than one value
at a time.
If a list of items (a list of car names, for example), storing the cars
in single variables could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
Creating an Array
Using an array literal is the easiest way to create
a JavaScriptArray.
Syntax:
var array_name = [item1, item2, ...];
var cars = ["Saab", "Volvo", "BMW"];
45. Array..
45
Using the JavaScript Keyword new:
var cars = new Array("Saab", "Volvo", "BMW");
Access the Elements of an Array:
array element is accessing by referring to the index number.
This statement accesses the value of the first element in cars:
var name = cars[0];
Changing an Array Element:
This statement changes the value of the first element in cars:
cars[0] = "Opel";
46. Functions
Code structure – splitting code into parts
Data comes in, processed, result returned
46
function average(a, b, c)
{
var total;
total = a+b+c;
return total/3;
}
Parameters come
in here.
Declaring variables
is optional.Type is
never declared.
Value returned
here.
47. Function Arguments
and ReturnValue
Functions are not required to return a value
When calling function it is not obligatory to
specify all of its arguments
The function has access to all the arguments
passed via arguments array
47
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4));
functions-demo.html
49. Some string common function
49
The length property returns the number of
characters that are in a string, using an integer.
Below is the basic code for accessing this
property.
var myString = "123456";
var length = myString.length;
document.write("The string is this long: " + length);
Out put:
The string is this long: 6
Length
50. Spilt
50
The ability to split up a string into separate
chunks has been supported in many
programming languages, and it is available in
JavaScript as well. If you have a long string
like “this is computer science faculty" and
want to store each name separately, you can
specify the space character " " and have the
split function create a new chunk every time
it sees a space.
51. 51
Let's start off with a little example that takes a string of
numbers and splits when it sees the number 5.That means
the delimiter for this example is 5. Notice that the split
function returns an array that we store into mySplitResult.
var myString = "123456789";
var mySplitResult = myString.split("5");
document.write("The first element is " + mySplitResult[0]);
document.write("<br />The second element is "
+ mySplitResult[1]);
Out put:
The first element is 1234
The second element is 6789
52. Search
52
The search() method searches a string for a
specified value and returns the position of
the match:
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
Out put: 7
53. 53
The most important thing to remember when creating a regular
expression is that it must be surrounded with slashes /regular
expression/.With that knowledge let's search a string to see if a
common name “2001" is inside it.
var myRegExp = /2001/;
var string1 = “the computer science facultyi s established in 2001 in IUST.";
var matchPos1 = string1.search(myRegExp);
if(matchPos1 != -1)
document.write("There was a match at position " + matchPos1);
else document.write("There was no match in the first string");
Out put: There was a match at position 44
For powerful search use regular expression
54. Extracting String Parts
54
There are 3 methods for extracting a part
of a string:
•slice(start, end)
•substring(start, end)
•substr(start, length)
55. Slice
55
slice() extracts a part of a string and returns the
extracted part in a new string.
The method takes 2 parameters: the start
position, and the end position (end not included).
This example slices out a portion of a string from
position 7 to position 12 (13-1):
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
The result of res will be: Banana
56. Slice…
56
If a parameter is negative, the position is counted
from the end of the string.
This example slices out a portion of a string from
position -12 to position -6:
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6);
The result of res will be: Banana
If you omit the second parameter, the method will slice out the rest of the string:
var res = str.slice(7);
var res = str.slice(-12);
57. Substring
57
substring() is similar to slice().
The difference is that substring() cannot accept
negative indexes.
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
The result of res will be: Banana
If you omit the second parameter, substring() will slice out the rest of the string.
58. substr
58
substr() is similar to Substring().
The difference is that the second parameter
specifies the length of the extracted part.
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
The result of res will be: Banana
If you omit the second parameter, substr() will slice out the rest of the string.
If the first parameter is negative, the position counts from the end of the string.
59. Replace
59
The replace() method replaces a specified value with
another value in a string:
var str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
Output Please visit W3Schools!
By default, the replace() method replaces only the
first match:
var str = "Please visit Microsoft and Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
60. 60
Replace…
By default, the replace() method is case sensitive. Writing
MICROSOFT (with upper-case) will not work:
var str = "Please visit Microsoft!";
var n = str.replace("MICROSOFT", "W3Schools");
To replace case insensitive, use a regular expression with
an /i (insensitive):
var str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools");
To replace all matches, use a regular expression with a /g
str = "Please visit Microsoft and Microsoft!";
n = str.replace(/Microsoft/g, "W3Schools");
61. Index of
61
The indexOf() method returns the index of (the position
of) the first occurrence of a specified text in a string:
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is
the third ...
The lastIndexOf() method returns the index of
the last occurrence of a specified text in a string:
62. 62
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
Output 22
<script type="text/javascript">
var aURL = "http://www.tizag.com/";
var aPosition = aURL.indexOf("www");
document.write("The position of www = " + aPosition);
</script >
Out put: The position of www = 7
Both methods accept a second parameter as the starting position
for the search:
var aURL = http://www.webtizag.com/";
var aPosition = aURL.indexOf(“w", 10);
document.write("The position of www = " + aPosition);
The position of www = 11
63. Search and IndexOf
The two methods, indexOf() and search(), are equal?
They accept the same arguments (parameters), and
return the same value?
But the differences are:
The search() method cannot take a second start
position argument.
The indexOf() method cannot take powerful search
values (regular expressions).
We will learn more about regular expressions later.
63
64. Search and IndexOf
The two methods, indexOf() and search(), are equal?
They accept the same arguments (parameters), and
return the same value?
But the differences are:
The search() method cannot take a second start
position argument.
The indexOf() method cannot take powerful search
values (regular expressions).
We will learn more about regular expressions in a later
chapter. 64
65. Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase():
var text1 = "Hello World!";
var text2 = text1.toUpperCase();
A string is converted to lower case with toLowerCase():
var text1 = "Hello World!";
var text2 = text1.toLowerCase();
65
66. charAt and charCodeAt
66
The charAt() method returns the character at a specified
index (position) in a string:
var str = "HELLO WORLD";
str.charAt(0); // returns H
The charCodeAt() method returns the unicode of the
character at a specified index in a string.
The method returns a UTF-16 code (an integer between 0
and 65535).
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
67. innerHTML
67
The easiest way to get or change the content of an
element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing
the content of HTML elements.
The innerHTML property can be used to get or change
any HTML element, including <html> and <body>.
Return the innerHTML property:
HTMLElementObject.innerHTML
Set the innerHTML property:
HTMLElementObject.innerHTML = text
68. Everything is Object
Every variable can be considered as object
For example strings and arrays have member
functions:
68
var test = "some string";
alert(test[7]); // shows letter 'r'
alert(test.charAt(5)); // shows letter 's'
alert("test".charAt(1)); //shows letter 'e'
alert("test".substring(1,3)); //shows 'es'
var arr = [1,3,4];
alert (arr.length); // shows 3
arr.push(7); // appends 7 to end of array
alert (arr[3]); // shows 7
objects.html
69. JavaScript Objects
69
Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
Object Properties Methods
car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
car.start()
car.drive()
car.brake()
car.stop()
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
70. JavaScript Objects…
70
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:“Toyota", model:"500", color:"white"};
The values are written as name:value pairs (name and value separated by a colon).
Object Properties
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Property PropertyValue
firstName John
lastName Doe
age 50
eyeColor blue
71. JavaScript Objects…
71
Spaces and line breaks are not important. An object definition can span multiple lines:
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Object Definition
You define (and create) a JavaScript object with an object literal:
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
72. JavaScript Objects…
72
objectName.propertyName
Accessing Object Properties
You can access object properties in two ways:
objectName["propertyName"]
<body>
<p>
There are two different ways to access an object property:
</p>
<p>You can use person.property or person["property"].</p>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>
document.getElementById("demo"
).innerHTML =
person["firstName"] + " " +
person["lastName"];
73. HTML Document Object Model
(HDOM)
When a web page is loaded, the browser creates
a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
74. Document Object Model (DOM)
74
With the object model, JavaScript gets all the
power it needs to create dynamic HTML:
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
JavaScript can create new HTML events in the page
75. 75
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"TheW3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of
a document.“
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
What is the DOM?
76. What is the HDOM?
The HTML DOM is a standard object model
and programming interface for HTML.
It defines:
76
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
In other words:The HTML DOM is a standard for how to get,
change, add, or delete HTML elements.
77. JavaScript HTML DOM Methods
HTML DOM methods are actions you can perform (on HTML
Elements).
HTML DOM properties are values (of HTML Elements) that you
can set or change.
77
The DOM Programming Interface
The HTML DOM can be accessed with JavaScript (and with
other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML
element).
A method is an action you can do (like add or deleting an HTML element).
78. JavaScript HTML DOM Methods…
The getElementById Method
The most common way to access an HTML
element is to use the id of the element.
The innerHTML Property
The easiest way to get the content of an element
is by using the innerHTML property.
The innerHTML property is useful for getting or
replacing the content of HTML elements.
78
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "HelloWorld!";
</script>
79. JavaScript HTML DOM Documen
The HTML DOM document object is the owner of
all other objects in your web page.
The HTML DOM Document Object
The document object represents your web page.
If you want to access any element in an HTML
page, you always start with accessing the
document object.
Next slide: some examples of how you can use
the document object to access and manipulate
HTML. 79
80. 80
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
Changing HTML Elements
Method Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(attribute, value) Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
81. Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
document.write(text) Write into the HTML output stream
Adding Events Handlers
Method Description
document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick
event
Note : that you don't use the "on" prefix for the event; use "click" instead of "onclick".
Syntax element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or "mousedown").
The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling
or event capturing.This parameter is optional.
82. DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML
document is a node:
The entire document is a document node
Every HTML element is an element node
The text inside HTML elements are text nodes
Every HTML attribute is an attribute node
All comments are comment
nodes
82
With the HTML DOM, all nodes in the
node tree can be accessed by JavaScript.
New nodes can be created, and all nodes
can be modified or deleted.
83. Node Relationships
83
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
In a node tree, the top node is called the root (or root node)
Every node has exactly one parent, except the root (which has no
parent)
A node can have a number of children
Siblings (brothers or sisters) are nodes with the same parent
<head>
<title>DOMTutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
84. 84
Node Relationships…
From the HTML above you can read:
<html> is the root node
<html> has no parents
<html> is the parent of <head> and <body>
<head> is the first child of <html>
<body> is the last child of <html>
and:
<head> has one child: <title>
<title> has one child (a text node): "DOM
Tutorial"
<body> has two children: <h1> and <p>
<h1> has one child: "DOM Lesson one"
<p> has one child: "Hello world!"
<h1> and <p> are siblings
and
Navigating Between Nodes
You can use the following node properties to navigate between nodes with JavaScript:
parentNode
childNodes[nodenumber]
firstChild
lastChild
nextSibling
previousSibling
Warning !
A common error in DOM processing is to
expect an element node to contain text.
The value of the text node can be accessed by the
node's innerHTML property, or the nodeValue.
85. Node Relationships…
85
Child Nodes and NodeValues
In addition to the innerHTML property, you can also use the childNodes and
nodeValue properties to get the content of an element.
The following example collects the node value of an <h1> element and copies it
into a <p> element:
<script>
var myText =
document.getElementById("intro").childNodes[0].nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
<h1 id="intro">My First Page</h1> <p id="demo">Hello!</p>
In the example above, getElementById is a method, while childNodes and nodeValue are
properties.
In this tutorial we use the innerHTML property. However, learning the method above is
useful for understanding the tree structure and the navigation of the DOM.
86. Node Relationships…
Using the firstChild property is the same as using childNodes[0]:
86
<script>
myText =
document.getElementById("intro").firstChild.nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
<h1 id="intro">My First Page</h1>
<p id="demo">Hello World!</p>
DOM Root Nodes
There are two special properties that
allow access to the full document:
document.body -The body of the
document
document.documentElement –The
full document
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates
the <b>document.body</b>
property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
87. Node Relationships…
87
Creating New HTML Elements (Nodes)
To add a new element to the HTML DOM, you must create the element (element
node) first, and then append it to an existing element.
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
<div id="div1">
<p id="p1">This is
a paragraph.</p>
<p id="p2">This is
another paragraph.
</p>
</div>
Creating new HTML Elements - insertBefore()
The appendChild() method in the previous example, appended the new element as the last
child of the parent.
If you don't want that you can use the insertBefore() method:
var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para,child);
88. Node Relationships…
88
Removing Existing HTML Elements
To remove an HTML element, you must know the parent of the element:
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
The method
node.remove() is
implemented in the DOM
4 specification.
But because of poor
browser support, you
should not use it.
Replacing HTML Elements
To replace an element to the HTML DOM, use the replaceChild() method:
<div id="div1">
<p id="p1">This is a
paragraph.</p>
<p id="p2">This is another
paragraph.</p>
</div>
var para = document.createElement("p");
var node =
document.createTextNode("This is
new.");
para.appendChild(node);
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.replaceChild(para,child);
90. Built-in Browser Objects
The browser provides some read-only data via:
window
The top node of the DOM tree
Represents the browser's window
document
holds information the current loaded document
screen
Holds the user’s display properties
navigtor
Holds information about the browser
History
Contain the browser history
location
Contain the current page URL
90
91. DOM Hierarchy – Example
91
window
navigator screen document history location
form
button form
form
92. Window Object Details
Properties
status: Specifies a temporary message that
appears on the status bar on the bottom of the
browser window.
Browser support
location: Identifies the URL associated with a
window object. It can be used to redirect the
client to another URL.
document: Refers to the current document
being displayed in the window. 92
93. Methods of Windows object
open(): Opens a new window with a specified document or opens the
document in the specified named window.
window.open("URL", "windowName", "featureList");
close(): Closes the current window. window.close();
alert(): Displays a message in a dialog box with an OK button.
confirm(): Displays a Confirm dialog box with OK and Cancel buttons.
prompt(): Displays a Prompt dialog box with a text field for entering a
value, with a OK & Cancel button.
blur() & focus(): Removes focus from or gives focus to a window.
93
98. Document and Location
document object
Provides some built-in arrays of specific objects
on the currently loaded Web page
document.location
Used to access the currently open URL or
redirect the browser
98
document.links[0].href = "yahoo.com";
document.write(
"This is some <b>bold text</b>");
document.location = "http://www.yahoo.com/";
99. The Screen Object
The screen object contains information about
the display
99
window.moveTo(0, 0);
x = screen.availWidth;
y = screen.availHeight;
window.resizeTo(x, y);
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Screen width is " + screen.width;
</script>
</body>
</html>
ScreenWidth: 1440
100. Regular Expressions
If you use HTML forms on your
website, and want to make sure
that your visitors submit valid data
on those forms, you might want to
consider using some regular
expressions in JavaScript
101. FormValidation – Example
101
function checkForm()
{
var valid = true;
if (document.mainForm.firstName.value == "") {
alert("Please type in your first name!");
document.getElementById("firstNameError").
style.display = "inline";
valid = false;
}
return valid;
}
…
<form name="mainForm" onsubmit="return checkForm()">
<input type="text" name="firstName" />
…
</form>
form-validation.html
102. Regular Expression syntax
/ Escapes special characters to literal and
literal characters to special
[…] Match any one character between the
brackets
[^…] Match any one character not between the
brackets
w, W Match any wordnon-word character
s, S Match any whitespace/non-whitespace
d, D Match any digit/non-digit
^, $ require match at beginning/end of a string
or in multi-line mode, beginning/end of
a line
a | b Match either a or b
+ Match previous term one or more times
^ Matches beginning of input
$ Matches end of input
103. FormValidation
/^[0-9]+$/ : Match values with Digits from 0 to 9
/^[1-5]+$/ : Match values with Digits from 1 to 5
/^[a-z]+$/ : Match values with alphabet from a to z
(small letter)
/^[A-Z]+$/ : Match values with alphabet from A to Z
/^[a-z0-9]+$/ : Match values with letter and Digits
/^[w-.+]+@[a-zA-Z0-9.-]+.[a-zA-z0-9]{2,4}$/
Match values with valid Email address
That all use with match function
104. The Math Object
The Math object provides some mathematical
functions
104
for (i=1; i<=20; i++) {
var x = Math.random();
x = 10*x + 1;
x = Math.floor(x);
document.write(
"Random number (" +
i + ") in range " +
"1..10 --> " + x +
"<br/>");
}
math.html
105. Math Objects
Math.PI; // returns 3.141592653589793
Math.round(4.7); // returns 5
Math.pow(8, 2); // returns 64
Math.sqrt(64); // returns 8
Math.abs(-4.7); // returns 4.7
Math.ceil(4.4); // returns 5
Math.floor(4.7); // returns 4
Math.Random(); //returns a random number
between 0 (inclusive), and 1 (exclusive): 105
106. The Date Object
The Date object provides date / calendar
functions
106
var now = new Date();
var result = "It is now " + now;
document.getElementById("timeField")
.innerText = result;
...
<p id="timeField"></p>
dates.html
107. Timing Events
107
The window object allows execution of code at specified time
intervals.
These time intervals are called timing events.
The two key methods to use with JavaScript are:
setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
The setTimeout() and setInterval() are both methods of the HTML
DOMWindow object.
108. Timers: setTimeout()
Make something happen (once) after a fixed
delay
108
var timer = setTimeout('bang()', 5000);
clearTimeout(timer);
5 seconds after this statement
executes, this function is called
Cancels the timer
109. Timers: setInterval()
Make something happen repeatedly at fixed
intervals
109
var timer = setInterval('clock()', 1000);
clearInterval(timer);
This function is called
continuously per 1 second.
Stop the timer.
110. Timer – Example
110
<script type="text/javascript">
function timerFunc() {
var now = new Date();
var hour = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
document.getElementById("clock").value =
"" + hour + ":" + min + ":" + sec;
}
setInterval('timerFunc()', 1000);
</script>
<input type="text" id="clock" />
timer-demo.html
111. What Are Cookies?
Small memory-resident pieces of information sent from a server to your
computer
Cookies were invented to solve the problem "how to remember
information about the user":
When a user visits a web page, his name can be stored in a
cookie.
Next time the user visits the page, the cookie "remembers" his
name.
Cookies are saved in name-value pairs like:
username=John Doe
When a browser request a web page from a server, cookies
belonging to the page is added to the request.This way the server
gets the necessary data to "remember" information about users.
112. Create a Cookie with JavaScript
JavaScript can create, read, and delete cookies with
the document.cookie property.
With JavaScript, a cookie can be created like this:
document.cookie="username=John Doe";
You can also add an expiry date (in UTC time). By default, the cookie
is deleted when the browser is closed:
document.cookie="username=John Doe; expires=Thu, 18 Dec
2013 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie
belongs to. By default, the cookie belongs to the current page.
document.cookie="username=John Doe; expires=Thu, 18 Dec
2013 12:00:00 UTC; path=/";
113. Read a Cookie with JavaScript
With JavaScript, cookies can be read like this:
var x = document.cookie;
document.cookie will return all cookies in one string much like:
cookie1=value; cookie2=value; cookie3=value;
Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you
create it:
document.cookie="username=John Smith;
expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
The old cookie is overwritten.
114. Delete a Cookie with JavaScript
Deleting a cookie is very simple. Just set the
expires parameter to a passed date:
document.cookie = "username=; expires=Thu, 01 Jan 1970
00:00:00 UTC";
Note : don't have to specify a cookie value when you
delete a cookie.
115. A Function to Set a Cookie
First, we create a function that stores the name of
the visitor in a cookie variable:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires; }
Example explained:
The parameters of the function above are the name of the cookie
(cname), the value of the cookie (cvalue), and the number of days
until the cookie should expire (exdays).
The function sets a cookie by adding together the cookie name,
the cookie value, and the expires string.
116. A Function to Get a Cookie
Then, we create a function that returns the value of a specified cookie:
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name)== 0) return c.substring(name.length,c.length); }
return "“; }
Function explained:
Take the cookiename as parameter (cname).
Create a variable (name) with the text to search for (cname + "=").
Split document.cookie on semicolons into an array called ca (ca =
document.cookie.split(';')).
Loop through the ca array (i=0;i<ca.length;i++), and read out each value c=ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of the
cookie (c.substring(name.length,c.length). If the cookie is not found, return "".
117. A Function to Check a Cookie
Last, we create the function that checks if a cookie is set.
If the cookie is set it will display a greeting.
If the cookie is not set, it will display a prompt box, asking for the
name of the user, and stores the username cookie for 365 days,
by calling the setCookie function:
function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
}else{
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365); } } }
118. JavaScript Errors -Throw andTry to Catch
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch,
regardless of the result.
ErrorsWill Happen!
When executing JavaScript code, different errors can occur.
Errors can be coding errors made by the programmer, errors due to
wrong input, and other unforeseeable things:
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!"); }
catch(err) {
document.getElementById("demo").innerHTML = err.message; }
</script>
119. JavaScript try and catch
119
The try statement allows you to define a block of code to be tested
for errors while it is being executed.
The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
The JavaScript statements try and catch come in pairs:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}