Lecture 6 HTML & Css

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 62

Web Development

HTML & CSS

Shermeen Adnan
JavaScript
• From Wikipedia:
• ... high-level, dynamic, untyped, and interpreted programming
language
• ... is prototype-based with first-class functions, …
• ... supporting object-oriented, imperative, and functional
programming ...
• … has an API for working with text, arrays, dates and regular
expressions
• Not particularly similar to Java: More like C crossed with Self/Scheme
– C-like statements with everything objects, closures, garbage collection, etc.
• Also known as ECMAScript
JavaScript
• What is JavaScript?
– JavaScript, often abbreviated as JS, is a high-level,
interpreted programming language that conforms to the
ECMAScript specification.
– Web pages are not the only place where JavaScript is used.
Many desktop and server programs use JavaScript. Node.js is
the best known. Some databases, like MongoDB and
CouchDB, also use JavaScript as their programming language.
• Why to study JavaScript?
– HTML to define the content of web pages
– CSS to specify the layout of web pages
– JavaScript to program the behavior of web pages
JavaScript
• What can you do with it?
– Build interactive web pages
– Web/mobile apps
– Real-time networking apps (chats and video streaming services)
– Command-line tools
– Games
• Where does JavaScript code run?
– It can be run outside the browser as well
• Originally designed to run in browsers (containing JS engine)
– FireFox : SpiderMonkey
chrome : v8
• Later Open source JavaScript engine chrome was embedded into C++ program called
“node”
• What is the difference between ECMAScript and JavaScript?
– ECMAScript (or ES) is a scripting-language specification standardized by Ecma
International to standardize JavaScript, so as to foster multiple independent
implementations.
Setting up the development environment
• To install third-party libraries
– node.js //nodejs.org
– Node.js is an open-source, cross-platform JavaScript run-time
environment that executes JavaScript code outside of a browser. 
• To check if it is already installed onto your computer
– In cmd prompt write
• Node –v (returning the version of node.js being installed on your machine)
• Live server
– Used to serve web applications
• ctrl+shift+p (package control : install package)  repository will be loaded
 browser sync
• This procedure will install package browser sync
• To launch browser sync in browsers other than chrome
• http://localhost:3000 (address from where our web application is served
from)
Setting up the development environment
• Go to "Tools > Build System > New Build System" in
the top bar
– { "cmd": ["node", "$file"], "selector": "source.js" }
– Save under USER folder with name node.sublime-build
• Go to "Tools > Build System > New Build System" in
the top bar
– { "cmd": ["C:/Program Files/nodejs/node.exe", "$file"],
"selector": "source.js" }
– Save this file as a JavaScript.sublime-build in “User”
directory
• To open JavaScript in chrome (ctrl+b)
• To open in sublime text (F7 key)
Setting up the development environment

• Highlight what you have missed while coding


– Ctrl+shift+p  install packages sublimelinter
– Ctrl+shift+p  install packages sublimelinter-
jshint
– npm install –g jshint (in cmd prompt)
JavaScript
• JavaScript makes HTML pages more dynamic and
interactive.
• The HTML <script> Tag
– The <script> tag is used to define a client-side script
(JavaScript).
– The <script> element either contains scripting statements, or
it points to an external script file through the src attribute.
• Common uses for JavaScript are image manipulation,
form validation, and dynamic changes of content.
– On the console
– Pop-up alerts
– Aritmetic operations
JavaScript Coding in browser
• <script>….</script>
– Can be added in <head> </head> and <body>
</body>
– Best practice for writing it is to write JavaScript
inside <body> before </body> as browser parses
files from top to bottom resulting in quick loading
of page content secondly the JavaScript code is
taking input from the html elements.
– Create a separate file *.js
• To access it in html code
– <script src="canvas.js"></script>
JavaScript Coding in browser
• Log a message on console
– console.log('hello world');
• string is written in single quotes ' ‘
• Terminate with ;
• // used to comment the document code
JavaScript Coding in node
• Open cmd
– Go to your directory of code and write
• node *.js
• Opening in sublime
– Integrate terminal
– ctrl+shift+p  terminal
– Re-open sublime
– ctrl+shift+t
Variables
• We use a variable to store data temporarily in
computer’s memory
• var or let is used to declare a variable
– var is function scoped and let is block scoped. It can
be said that a variable declared with var is defined
throughout the program as compared to let.
• The default value of a variable is “undefined”
• To declare value of a variable constant
– const varname=value;
Variables
• JavaScript Identifiers
– 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 _
– Names are case sensitive (y and Y are different variables)
– Reserved words (like JavaScript keywords) cannot be used as names
– JavaScript identifiers are case-sensitive.
– Names can not start with number or hyphen (-)
Types of values assigned to variables
• primitive./ value types
• A primitive data value is a single simple data value with no
additional properties and methods.
– String let name= “student“; //string literal
– Number let age=22; //number literal
– Boolean let isApproved=false; //boolean literal
– Undefined let firstName=undefined;
– Null let selectColor=null; //type=object
• Reference types
– Object //type=object
– Array //type=object
– Function //type=function
Dynamic typing
• JavaScript is a dynamic language
– Language are of 2 types
• Statically-typed
– String name = student
• Dynamically-typed
– Let name = 123

• To find the type of a JavaScript variable.


– typeof identifier (write in console)
– All type of numbers are just numbers
– Booleans are often used in conditional testing.
• ctrl+l (to clear console)
Types of values assigned to variables
• Object
• JavaScript objects are written with curly braces {}.
• Object properties are written as name:value pairs,
separated by commas.
– let person= { name : 'student' , age : 22};
// to access values of object dot notation
person.name
// to access values of object bracket notation
person['name ']
console.log(person);
dot vs bracket notation
• Dot notation: • Bracket notation:
– Property identifies can – Property identifiers have
only be alphanumeric to be a String or a
(and _ and $) variable that references
– Property identifiers a String.
cannot start with a – It is okay to use
number. variables, spaces, and
– Property identifiers Strings that start with
cannot contain variables. numbers
– OK —  – OK — 
obj.prop_1, obj.prop$ obj["1prop"], obj["prop
– Not OK —  name"]
obj.1prop, obj.prop name
Object Methods
• Objects can also have methods.
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.
• A method is a function stored as a property.
– var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
The this Keyword
• The JavaScript this keyword refers to the object it
belongs to.
• It has different values depending on where it is used:
– In a method, this refers to the owner object.
– Alone, this refers to the global object.
– In a function, this refers to the global object.
– In a function, in strict mode, this is undefined.
– In an event, this refers to the element that received the
event.
– Methods like call(), and apply() can refer this to any object.
Object Methods
• Do Not Declare Strings, Numbers, and Booleans as
Objects!
• When a JavaScript variable is declared with the
keyword "new", the variable is created as an object:
– var x = new String();         // Declares x as a String object
var y = new Number();    // Declares y as a Number object
var z = new Boolean();   // Declares z as a Boolean object
• Avoid String, Number, and Boolean objects. They
complicate your code and slow down execution
speed.
JavaScript Events
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can "react" on these
events.
• 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.
– HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.
• <button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>
• <button onclick="this.innerHTML=Date()">The time is?</button>
JavaScript Events
• Function
– <button onclick="displayDate()">The time is?</button>

– <script>
– function displayDate() {
– document.getElementById("demo").innerHTML = Date();
–}
– </script>

– <p id="demo"></p>
Common events
String Methods and Properties
• String Length
– The length property returns the length of a string:
• <p id="demo"></p>

• <script>
• var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
• document.getElementById("demo").innerHTML =
txt.length;
• </script>
String Methods and Properties
• Finding a String in a String
– The indexOf() method returns the index of (the position of)
the first occurrence of a specified text in a string:
• <p id="demo"></p>

• <script>
• var str = "Please locate where 'locate' occurs!";
• var pos = str.indexOf("locate");
• document.getElementById("demo").innerHTML = pos;
• </script>
– The lastIndexOf() method returns the index of the last occurrence of a
specified text in a string
– Both indexOf(), and lastIndexOf() return -1 if the text is not found.
String Methods and Properties
• Searching for a String in a String
– The search() method searches a string for a specified value and
returns the position of the match:
• <p id="demo"></p>

• <script>
• var str = "Please locate where 'locate' occurs!";
• var pos = str.search("locate");
• document.getElementById("demo").innerHTML = pos;
• </script>
• The only difference with indexOf() is that the search() method
cannot take a second start position argument.
String Methods and Properties
• Extracting String Parts
– There are 3 methods for extracting a part of a string:
• slice(start, end)
• substring(start, end)
• substr(start, length)
– The slice() Method
• 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
– <p id="demo"></p>
– <script>
– var str = "Apple, Banana, Kiwi";
– var res = str.slice(7,13);
– document.getElementById("demo").innerHTML = res;
– </script>

• Slice can also accept negative indexes.


String Methods and Properties
• The substring() Method
– substring() is similar to slice().
– The difference is that substring() cannot accept negative
indexes.
– If you omit the second parameter, substring() will slice out the
rest of the string.
• <p id="demo"></p>
• <script>
• var str = "Apple, Banana, Kiwi";
• var res = str.substring(7,13);
• document.getElementById("demo").innerHTML = res;
• </script>
String Methods and Properties
• The substr() Method
– substr() is similar to slice().
– The difference is that the second parameter specifies the length of the
extracted part.
– 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.
• <p id="demo"></p>
• <script>
• var str = "Apple, Banana, Kiwi";
• var res = str.substr(7,6);
• document.getElementById("demo").innerHTML = res;
• </script>
String Methods and Properties
• Replacing String Content
– The replace() method replaces a specified value with another value in a
string
– The replace() method does not change the string it is called on. It
returns a new string.
– By default, the replace() method replaces only the first match
– By default, the replace() method is case sensitive.
• <button onclick="myFunction()">Try it</button>
• <p id="demo">Please visit Microsoft!</p>
• <script>
• function myFunction() {
• var str = document.getElementById("demo").innerHTML;
• var txt = str.replace("Microsoft","W3Schools");
• document.getElementById("demo").innerHTML = txt;
• }
• </script>
String Methods and Properties
• use a regular expression with an /i flag
(insensitive)
– str.replace(/MICROSOFT/i, "W3Schools");
• Replacing all the occurrences
– str.replace(/Microsoft/g,"W3Schools");
• Converting to Upper and Lower Case
– A string is converted to upper case with toUpperCase():
• var text1 = "Hello World!";       
var text2 = text1.toUpperCase();
var text3 = text2.toLowerCase(); 
String Methods and Properties
• The concat() Method
• concat() joins two or more strings:
– <p id="demo"></p>
– <script>
– var text1 = "Hello";
– var text2 = "World!";
– var text3 = text1.concat(" ",text2);
– document.getElementById("demo").innerHTML = text3;
– </script>
• All string methods return a new string. They don't modify the original
string.
Formally said: Strings are immutable: Strings cannot be changed, only
replaced.
String Methods and Properties
• String.trim()
• The trim() method removes whitespace from both sides of a
string
– <button onclick="myFunction()">Try it</button>

– <script>
– function myFunction() {
– var str = " Hello World! ";
– alert(str.trim());
–}
– </script>
Arrays
• JavaScript arrays are written with square
brackets.
• Array items are separated by commas.
– Let selectedColors=['red' , 'blue' , 'green'];
– Length of array
• console.log(selectedColors.length);
• Array indexes are zero-based, which means
the first item is [0], second is [1], and so on.
Functions
• A block of code designed to perform a particular task.
• Executed when "something" invokes it (calls it).
• A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ().
• Function names have same rules as variables.
• The parentheses may include parameter names separated
by commas: (parameter1, parameter2, ...)
• The code to be executed, by the function, is placed inside
curly brackets: {}
– function name(parameter1, parameter2, parameter3) {
  // code to be executed
}
– Function_name(argument);
Function Invocation
• The code inside the function will execute
when "something" invokes (calls) the
function:
– When an event occurs (when a user clicks a
button)
– When it is invoked (called) from JavaScript code
– Automatically (self invoked)
Function Return
• When JavaScript reaches a return statement,
the function will stop executing.
• If the function was invoked from a statement,
JavaScript will "return" to execute the code
after the invoking statement.
• Functions often compute a return value. The
return value is "returned" back to the "caller"
Types of Functions
• Performing a task
– function greet(Fname, Lname) {
– console.log('Greetings' + ' ' + Fname + ' ' + Lname);
–}
– greet('hello', 'girl');
• Calculating a value
– function square(number) {
– return number * number;
–}
– let number = square(11);
– console.log(number);
Why Functions?
• You can reuse code: Define the code once, and
use it many times.
• You can use the same code many times with
different arguments, to produce different
results.
JavaScript Arithmetic Operators

x ** y produces the same result as Math.pow(x,y)


JavaScript Escape Sequence
• \' single quote
• \'' double quote
• \\ backslash
• \n newline
• \r carriage return
• \t tab
• \b backspace
• \f form feed
JavaScript Assignment Operators
JavaScript String Operators
• The + operator can also be used to add
(concatenate) strings.
– var txt3 = txt1 + " " + txt2;
• The += assignment operator can also be used
to add (concatenate) strings
– txt1 += "nice day";
JavaScript Comparison Operators
JavaScript Logical Operators
JavaScript Type Operators
JavaScript Bitwise Operators
• Bit operators work on 32 bits numbers.
• Any numeric operand in the operation is converted into a 32 bit
number. The result is converted back to a JavaScript number.
JavaScript
• To select an HTML element, JavaScript very often
uses the document.getElementById() method.
– <p id="demo"></p>

– <script>
– document.getElementById("demo").innerHTML =
"Hello JavaScript!";
– </script>
• JavaScript accepts both double and single quotes
JavaScript
• <!DOCTYPE html>
• <html>
• <body>

• <h1>My First JavaScript</h1>

• <button type="button"
• onclick="document.getElementById('demo').innerHTML = Date()">
• Click me to display Date and Time.</button>

• <p id="demo"></p>

• </body>
• </html>
what JavaScript can do?
• JavaScript can change HTML content
– <!DOCTYPE html>
– <html>
– <body>
– <h1>My First JavaScript</h1>

– <p>JavaScript can change the content of an HTML element:</p>

– <button type="button" onclick="myFunction()">Click Me!</button>

– <p id="demo">This is a demonstration.</p>

– <script>
– function myFunction() {
– document.getElementById("demo").innerHTML = "Hello JavaScript!";
–}
– </script>

– </body>
– </html>
what JavaScript can do?
• JavaScript can change HTML styles
– <!DOCTYPE html>
– <html>
– <body>
– <h1>My First JavaScript</h1>

– <p id="demo">JavaScript can change the style of an HTML element.</p>

– <script>
– function myFunction() {
– document.getElementById("demo").style.fontSize = "25px";
– document.getElementById("demo").style.color = "red";
– document.getElementById("demo").style.backgroundColor = "yellow";
–}
– </script>

– <button type="button" onclick="myFunction()">Click Me!</button>

– </body>
– </html>
what JavaScript can do?
• JavaScript can change HTML attributes
– <!DOCTYPE html>
– <html>
– <body>
– <script>
– function light(sw) {
– var pic;
– if (sw == 0) {
– pic = "pic_bulboff.gif"
– } else {
– pic = "pic_bulbon.gif"
– }
– document.getElementById('myImage').src = pic;
–}
– </script>

– <img id="myImage" src="pic_bulboff.gif" width="100" height="180">


– <p>
– <button type="button" onclick="light(1)">Light On</button>
– <button type="button" onclick="light(0)">Light Off</button>
– </p>

– </body>
– </html>
The HTML <noscript> Tag

• The <noscript> tag is used to provide an alternate


content for users that have disabled scripts in their
browser or have a browser that doesn't support
client-side scripts:
– Example
• <script>
document.getElementById("demo").innerHTML = "Hello
JavaScript!";
</script>

<noscript>Sorry, your browser does not support JavaScript!


</noscript>
JavaScript Output
• 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().
Using document.write()
• The write() method writes HTML expressions or JavaScript code
to a document.
– <script>
document.write(5 + 6);
</script>
• Used for testing: If it is used after an HTML document is fully
loaded, it will delete all existing HTML.
– <button type="button" onclick="document.write(5 + 6)">Try
it</button>
• When this method is not used for testing, it is often used to
write some text to an output stream opened by
the document.open() method.
• The document.writeln() method is similar to write(), only it
adds a newline character after each statement.
• The document.write() method should only be used for testing.
Using window.alert()
• The alert() method displays an alert box with a
specified message and an OK button.
• An alert box is often used if you want to make sure
information comes through to the user.
• Note: The alert box takes the focus away from the
current window, and forces the browser to read the
message. Do not overuse this method, as it prevents
the user from accessing other parts of the page until
the box is closed.
– Window.alert("opening the doc");
JavaScript Keywords
• JavaScript statements often start with a keyword to
identify the JavaScript action to be performed.
JavaScript Comments
• Not all JavaScript statements are "executed".
• Code after double slashes // or
between /* and */ is treated as a comment.
HTML File Paths

• A file path describes the location of a file in a web site's folder


structure.
• File paths are used when linking to external files like:
– Web pages
– Images
– Style sheets
– JavaScripts
HTML File Paths
• Absolute File Paths
– An absolute file path is the full URL to an internet file
• Relative File Paths
– A relative file path points to a file relative to the current page.
• Best Practice
– It is best practice to use relative file paths (if possible).
– When using relative file paths, your web pages will not be
bound to your current base URL. All links will work on your
own computer (localhost) as well as on your current public
domain and your future public domains.
HTML Layout
• Websites often display content in multiple columns (like a
magazine or newspaper).
• HTML5 offers new semantic elements that define the different
parts of a web page:
– <header> - Defines a header for a document or a section
– <nav> - Defines a container for navigation links
– <section> - Defines a section in a document
– <article> - Defines an independent self-contained article
– <aside> - Defines content aside from the content (like a sidebar)
– <footer> - Defines a footer for a document or a section
– <details> - Defines additional details
– <summary> - Defines a heading for the<details> element
HTML Layout Techniques
• There are five different ways to create
multicolumn layouts. Each way has its pros
and cons:
– HTML tables (not recommended)
– CSS float property
– CSS flexbox
– CSS framework
– CSS grid

You might also like