0% found this document useful (0 votes)
20 views95 pages

Web Development

The document provides an introduction to web development, covering key concepts such as the World Wide Web, URLs, and the components of a webpage. It explains the differences between static and dynamic websites, outlines the advantages of having a website, and details HTML elements and tags used in webpage design. Additionally, it discusses the structure and formatting of HTML, including examples of various tags and their attributes.

Uploaded by

Joshua Bachuba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views95 pages

Web Development

The document provides an introduction to web development, covering key concepts such as the World Wide Web, URLs, and the components of a webpage. It explains the differences between static and dynamic websites, outlines the advantages of having a website, and details HTML elements and tags used in webpage design. Additionally, it discusses the structure and formatting of HTML, including examples of various tags and their attributes.

Uploaded by

Joshua Bachuba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 95

WEB

DEVELOPMENT
INTRODUCTION TO WEBPAGE DESIGN

WEB
Is a complex system of interconnected elements.
World Wide Web (abbreviated WWW or the Web)
Is an information space where documents and other web resources are identified
by Uniform Resource Locators (URLs), interlinked by hypertext links, and can be
accessed via the Internet.
Uniform Resource Locator (URL)
Is a reference to a web resource that specifies its location on a computer network
and a mechanism for retrieving it. A URL is a specific type of Uniform Resource
Identifier (URI), although many people use the two terms interchangeably.
Hypertext
Is text displayed on a computer display or other electronic devices with references
(hyperlinks) to other text that the reader can immediately access, or where text
can be revealed progressively at multiple levels of detail (also called StretchText).
INTRODUCTION TO WEBPAGE ………….

Hyperlink
hyperlink, or simply a link, is a reference to data that the reader can directly follow
either by clicking, tapping, or hovering.
A user following hyperlinks is said to navigate or browse the hypertext.
Browser
a computer program with a graphical user interface for displaying HTML files, used to
navigate the World Wide Web.
Surf
Is the activity of moving from site to site(from one website to another) on the Internet.
Webpage: a hypertext document connected to the World Wide Web.
INTRODUCTION TO WEBPAGE ………….

Website
Is a collection of related web pages, including multimedia content, typically identified
with a common domain name, and published on at least one web server.
Domain name
Is a unique reference that identifies a web site on the internet, for example loyola.ac.tz

A domain name always includes the top-level domain (TLD), which in loyola case is tz.
the ac part is shorthand for academic and combined .ac.tz is called a second-level
domain (SLD).
Server: Is a computer that provide services to other computers called client
Client: Is a computer that receives services from the server.
INTRODUCTION TO WEBPAGE ………….

COMPONENTS OF URL
1. Protocal: Is the set of rules and conventions governing the interactions between
participants in a distributed computing application. E.g http:// or https://
http stands for HyperText Transfer Protocal
2. Domain name: Is a unique reference that identifies a web site on the internet, for
example loyola.ac.tz
3. Directory: Is a collection of objects
4. Filename and Extension
INTRODUCTION TO WEBPAGE ………….

WORLD WIDE WEB

Definition - What does World Wide Web (WWW) mean?

The World Wide Web (WWW) is a network of online content that is formatted in HTML
and accessed via HTTP.
The term refers to all the interlinked HTML pages that can be accessed over the
Internet. The World Wide Web was originally designed in 1991 by Tim Berners-Lee
while he was a contractor at CERN.
The World Wide Web is what most people think of as the Internet. It is all the Web
pages, pictures, videos and other online content that can be accessed via a Web
browser.
TYPES OF WEBSITE

Static website:
A static website is one that has web pages stored on the server in the format that is
sent to a client web browser.
It is primarily coded in Hypertext Markup Language (HTML); Cascading Style Sheets
(CSS) are used to control appearance beyond basic HTML.

Dynamic website:
A dynamic website is one that changes or customizes itself frequently and
automatically. Server-side dynamic pages are generated "on the fly" by computer code
that produces the HTML (CSS are responsible for appearance and thus, are static files).
Programming languages used to create such website are PHP, Java Servlets, Java Server
Page, Python, Ruby etc.
MAIN CATEGORIES OF WEBSITES:

• Web Based Sales – Selling products or services on-line / E-commerce


• Offline Sales – Selling products or services but from “brick-and-
mortar” stores; wholesale or retail
• Generating Leads – Getting new business, new customers
• Market Awareness – Letting consumers know about a particular
product or service
• Informative or Entertaining – Just for the sake of sharing info or
entertainment with others
• Influential or Persuasion – Trying to influence a person to lean
towards a new direction, product, or stance
ADVANTAGES OF HAVING WEBSITE

Less Expensive
Having a website will make promoting your company less expensive. Many versions of
offline advertising available on the internet are sometimes free.
Advertising
There are lots of ways to advertise your products or services through the internet. One
example is Facebook ads, an advertising feature offered through Facebook.
Satisfaction
Make it easy for your customers to purchase from you! Many will be more likely to visit
your website, rather than driving a car to your physical location and browsing for your
products.
Increase Customers
The internet offers a global community. With a website, your business will be visible
around the world which will help you generate more customers.
ADVANTAGES OF HAVING WEBSITE

Accessibility
An online site can be visited any time of the day or night. People will look to your site
instead of going to your shop because it is more accessible.
Access to Info
You can access the progress of your website and view all its pages. You can even make
an update anytime, making it much less expensive than printed material.
Better Relationship
Having a website can build better relationships with your customers. You can send
messages instantly to your customers through email. Also, your customers can review
your products online and can also leave feedback for you and your business.
Increase Sales
You can drive more people to your site by consistently updating and promoting the
contents of your site.
ADVANTAGES OF HAVING WEBSITE

Opportunity
A website gives you the opportunity to prove your credibility. You have to tell your
customers why you deserve their trust through your website.
Long Term Clients
A client is your regular customer. He is buying your products or services daily or
contractually. Having a website gives you a chance to gain more clients that can help
your business grow.
html

ELEMENTS OF A WEB PAGE

The Doctype declaration.


This provides the web browser (or other user agent) with information about the type
of markup language in which the page is written, which may or may not affect the way
the browser renders the content.
i.e <!DOCTYPE html>

Html
Immediately after the doctype comes the htmlelement—this is the root element of the
document tree and everything that follows is a descendant of that root element.
i.e <html> </html>
Head
The head element contains metadata—information that describes the document itself,
or associates it with related resources, such as scripts and style sheets.
WHAT IS HTML?

• HTML is an acronym which stands for Hyper Text Markup Language.


• Hyper Text: Hyper Text simply means "Text within Text". A text has a link
within it, is a hypertext. Every time when you click on a word which brings
you to a new webpage, you have clicked on a hypertext.
• Markup language: A markup language is a programming language that is
used make text more interactive and dynamic. It can turn a text into images,
tables, links etc.
• An HTML document is made of many HTML tags and each HTML tag contains
different content.
EXAMPLE

<!DOCTYPE>
<html>
<body>
<h1>Write Your First Heading</h1>
<p>Write Your First Paragraph.</p>
</body>
</html>
DESCRIPTION OF HTML EXAMPLE

• DOCTYPE: It defines the document type.


• html : Text between html tag describes the web document.
• body : Text between body tag describes the body content of the page
that is visible to the end user.
• h1 : Text between h1 tag describes the heading of the webpage.
• p : Text between p tag describes the paragraph of the webpage.
FEATURES OF HTML

1) It is a very easy and simple language. It can be easily understood and modified.
2) It is very easy to make effective presentation with HTML because it has a lot of
formatting tags.
3) It is a markup language so it provides a flexible way to design web pages along
with the text.
4) It facilitates programmers to add link on the web pages (by html anchor tag) , so it
enhances the interest of browsing of the user.
5) It is platform-independent because it can be displayed on any platform like
Windows, Linux and Macintosh etc.
6) It facilitates the programmer to add Graphics, Videos, and Sound to the web
pages which makes it more attractive and interactive.
HTML TAGS

• HTML tags contain three main parts: opening tag, content and closing tag. But
some HTML tags are unclosed tags.
• When a web browser reads an HTML document, browser reads it from top to
bottom and left to right. HTML tags are used to create HTML documents and
render their properties. Each HTML tags have different properties.
Syntax
• <tag> content </tag>
• HTML Tag Examples
• Note: HTML Tags are always written in lowercase letters.
UNCLOSED HTML TAGS

• Some HTML tags are not closed, for example br and hr.
• <br> Tag: br stands for break line, it breaks the line of the code.
• <hr> Tag: hr stands for Horizontal Rule. This tag is used to put a line
across the webpage.
TAGS

HTML Meta Tags


• DOCTYPE, title, link, meta and style
HTML Text Tags
<p>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <strong>, <em>,
<abbr>, <acronym>, <address>, <bdo>, <blockquote>, <cite>, <q>,
<code>, <ins>, <del>, <dfn>, <kbd>, <pre>, <samp>, <var> and
<br>
TAGS

HTML Link Tags


• <a> and <base>
HTML Image and Object Tags
• <img>, <area>, <map>, <param> and <object>
TAGS

HTML Form Tags


• form, input, textarea, select, option, optgroup, button, label, fieldset
and legendHTML List Tags
HTML List Tags
• <ul>, <ol>, <li>, <dl>, <dt> and <dd>
HTML Table Tags
• table, tr, td, th, tbody, thead, tfoot, col, colgroup and caption
HTML FORMATTING

HTML Formatting is a process of formatting text for better look and


feel. There are many formatting tags in HTML. These tags are used to
make text bold, italicized, or underlined. There are almost 12 options
available that how text appears in HTML and XHTML.
Here, we are going to learn 12 HTML formatting tags.
1) Bold Text
If you write anything within <b>............</b> element, is shown in bold
letters.
See this example:
<p> <b>Write Your First Paragraph in bold text.</b></p>
HTML FORMATTING ……………….

2) Italic Text
If you write anything within <i>............</i> element, is shown in italic letters.
See this example:
<p> <i>Write Your First Paragraph in italic text.</i></p>
3) HTML Marked formatting
If you want to mark or highlight a text, you should write the content within
<mark>.........</mark>.
See this example:
<h2> I want to put a <mark> Mark</mark> on your face</h2>
HTML FORMATTING………….

4) Underlined Text
If you write anything within <u>.........</u> element, is shown in underlined text.
See this example:
<p> <u>Write Your First Paragraph in underlined text.</u></p>
5) Strike Text
Anything written within <strike>.......................</strike> element is displayed
with strikethrough. It is a thin line which cross the statement.
See this example:
<p> <strike>Write Your First Paragraph with strikethrough</strike>.</p>
HTML HEADING

A HTML heading or HTML h tag can be defined as a title or a subtitle which you want to display on the
webpage. When you place the text within the heading tags <h1>.........</h1>, it is displayed on the
browser in the bold format and size of the text depends on the number of heading.
There are six different HTML headings which are defined with the <h1> to <h6> tags.
h1 is the largest heading tag and h6 is the smallest one. So h1 is used for most important heading
and h6 is used for least important.
See this example:
<h1>Heading no. 1</h1>
<h2>Heading no. 2</h2>
<h3>Heading no. 3</h3>
<h4>Heading no. 4</h4>
<h5>Heading no. 5</h5>
<h6>Heading no. 6</h6>
HTML PARAGRAPH

HTML paragraph or HTML p tag is used to define a paragraph in a


webpage. Let's take a simple example to see how it work. It is a notable
point that a browser itself add an empty line before and after a
paragraph.
See this example:
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
SPACE INSIDE HTML PARAGRAPH

If you put a lot of spaces inside the HTML p tag, browser removes extra spaces
and extra line while displaying the page. The browser counts number of spaces
and lines as a single one.
<p>
I am
going to provide
you a tutorial on HTML
and hope that it will
be very beneficial for you.
</p>
HTML ANCHOR

The HTML anchor tag defines a hyperlink that links one page to another
page. The "href" attribute is the most important attribute of the HTML a tag.
href attribute of HTML anchor tag
The href attribute is used to define the address of the file to be linked. In
other words, it points out the destination page.
The syntax of HTML anchor tag is given below.
<a href = "..........."> Link Text </a>
Let's see an example of HTML anchor tag.
<a href="second.html">Click for Second Page</a>
ATTRIBUTES

HTML attribute is a modifier of an HTML element type.


• Attributes provide additional information about an element
• Attributes are always specified in the start tag
• Attributes usually come in name/value pairs like:
name="value“
Example
<a href=“home.html”>Home</a>
HTML IMAGE

HTML img tag is used to display image on the web page. HTML img tag is an empty tag that
contains attributes only, closing tags are not used in HTML image element.
Let's see an example of HTML image.
<h2>HTML Image Example</h2>
<img src="good_morning.jpg" alt="Good Morning Friends"/>
Attributes of HTML img tag
The src and alt are important attributes of HTML img tag. All attributes of HTML image tag are
given below.
1) src
It is a necessary attribute that describes the source or path of the image. It instructs the browser
where to look for the image on the server.
The location of image may be on the same directory or another server.
ATTRIBUTES OF HTML IMG TAG

2) alt
The alt attribute defines an alternate text for the image, if it can't be displayed. The
value of the alt attribute describe the image in words. The alt attribute is
considered good for SEO prospective.
3) width
It is an optional attribute which is used to specify the width to display the image. It
is not recommended now. You should apply CSS in place of width attribute.
4) height
It specifies the height of the image. The HTML height attribute also supports iframe,
image and object elements. It is not recommended now. You should apply CSS in
place of height attribute.
HTML TABLE

HTML table tag is used to display data in tabular form (row * column).
There can be many columns in a row.
HTML tables are used to manage the layout of the page e.g. header
section, navigation bar, body content, footer section etc. But it is
recommended to use div tag over table to manage the layout of the page .
HTML Table Tags
Tag Description
<table> It defines a table.
<tr> It defines a row in a table.
HTML TABLE TAGS

<th> It defines a header cell in a table.


<td> It defines a cell in a table.
<caption> It defines the table caption.
<colgroup> It specifies a group of one or more columns in a table for
formatting.
<col> It is used with <colgroup> element to specify column properties for
each column.
<tbody> It is used to group the body content in a table.
<thead> It is used to group the header content in a table.
<tfooter> It is used to group the footer content in a table.
HTML TABLE EXAMPLE

<table>

<tr><th>First_Name</th><th>Last_Name</th><th>Marks</th></tr>
<tr><td>Sonoo</td><td>Jaiswal</td><td>60</td></tr>
<tr><td>James</td><td>William</td><td>80</td></tr>
<tr><td>Swati</td><td>Sironi</td><td>82</td></tr>
<tr><td>Chetna</td><td>Singh</td><td>72</td></tr>
</table>
TABLES: ROWSPAN AND COLSPAN

Colspan and Rowspan A table is divided into rows and each row is divided
into cells. In some situations we need the Table Cells span across (or
merged) more than one column or row.
<tr>
<th rowspan="2">Row</th>
<th colspan="4">&nbsp;Column</th>
</tr>
HTML LISTS

HTML Lists are used to specify lists of information. All lists may contain
one or more list elements. There are three different types of HTML lists:

Ordered List or Numbered List (ol)


Unordered List or Bulleted List (ul)
Description List or Definition List (dl)
HTML ORDERED LIST OR NUMBERED LIST

In the ordered HTML lists, all the list items are marked with numbers. It is
known as numbered list also. The ordered list starts with <ol> tag and
the list items start with <li> tag.
<ol>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ol>
HTML UNORDERED LIST OR BULLETED
LIST
In HTML Unordered list, all the list items are marked with bullets. It is also
known as bulleted list also. The Unordered list starts with <ul> tag and
list items start with the <li> tag.
<ul>
<li>Aries</li>
<li>Bingo</li>
<li>Leo</li>
<li>Oracle</li>
</ul>
HTML ORDERED LIST | HTML NUMBERED LIST

HTML Ordered List or Numbered List displays elements in numbered


format. The HTML ol tag is used for ordered list. There can be different
types of numbered list:

Numeric Number (1, 2, 3)


Capital Roman Number (I II III)
Small Romal Number (i ii iii)
Capital Alphabet (A B C)
Small Alphabet (a b c)
TO REPRESENT DIFFERENT ORDERED LISTS, THERE ARE
5 TYPES OF ATTRIBUTES IN <OL> TAG.

Type Description
Type "1" This is the default type. In this type, the list items are numbered
with numbers.
Type "I" In this type, the list items are numbered with upper case roman
numbers.
Type "i" In this type, the list items are numbered with lower case roman
numbers.
Type "A" In this type, the list items are numbered with upper case letters.
Type "a" In this type, the list items are numbered with lower case letters.
HTML ORDERED LIST EXAMPLE

<ol>
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ol>
HTML ORDERED LIST EXAMPLE

ol type="I"
Let's see the example to display list in roman number uppercase.
<ol type="I">
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ol>
START ATTRIBUTE

The start attribute is used with ol tag to specify from where to start the list
items.
<ol type="1" start="5"> : It will show numeric values starting with "5".
<ol type="A" start="5"> : It will show capital alphabets starting with "E".
<ol type="a" start="5"> : It will show lower case alphabets starting with
"e".
<ol type="I" start="5"> : It will show Roman upper case value starting with
"V".
<ol type="i" start="5"> : It will show Roman lower case value starting with
"v".
START ATTRIBUTE

Example
<ol type="i" start="5">
<li>HTML</li>
<li>Java</li>
<li>JavaScript</li>
<li>SQL</li>
</ol>
HTML FORM

An HTML form is a section of a document which contains controls such as text


fields, password fields, checkboxes, radio buttons, submit button, menus etc.
An HTML form facilitates the user to enter data that is to be sent to the
server for processing.
Why use HTML Form
HTML forms are required if you want to collect some data from of the site
visitor.
For example: If a user want to purchase some items on internet, he/she must
fill the form such as shipping address and credit/debit card details so that
item can be sent to the given address.
HTML FORM SYNTAX

<form action="server url" method="get|post">


//input controls e.g. textfield, textarea, radiobutton, button
</form>
HTML FORM TAGS
HTML TEXTFIELD CONTROL

The type="text" attribute of input tag creates textfield control also


known as single line textfield control. The name attribute is optional, but
it is required for the server side component such as JSP, ASP, PHP etc.
<form>
First Name: <input type="text" name="firstname"/> <br/>
Last Name: <input type="text" name="lastname"/> <br/>
</form>
LABEL TAG IN FORM

It is considered better to have label in form. As it makes the code


parser/browser/user friendly.
If you click on the label tag, it will focus on the text control. To do so, you need
to have for attribute in label tag that must be same as id attribute of input tag.
<form>
<label for="firstname">First Name: </label>
<input type="text" id="firstname" name="firstname"/> <br/>
<label for="lastname">Last Name: </label>
<input type="text" id="lastname" name="lastname"/> <br/>
</form>
HTML PASSWORD FIELD CONTROL

The password is not visible to the user in password field control.


<form>
<label for="password">Password: </label>
<input type="password" id="password" name="password"/>
<br/>
</form>
HTML EMAIL FIELD CONTROL

The email field validates the text for correct email address. You must use
@ and . in this field.
<form>
<label for="email">Email: </label>
<input type="email" id="email" name="email"/> <br/>
</form>
RADIO BUTTON CONTROL

The radio button is used to select one from multiple options. It is used in gender,
quiz questions etc.
If you use one name for all the radio buttons, only one radio button can be selected
at a time.
<form>
<label for="gender">Gender: </label>
<input type="radio" id="gender" name="gender" value="male"/>Male
<input type="radio" id="gender" name="gender"
value="female"/>Female <br/>
</form>
CHECKBOX CONTROL

The checkbox control is used to check multiple options from given checkboxes.
<form>
Hobby:<br>
<input type="checkbox" id="cricket" name="cricket" value="cricket"/>
<label for="cricket">Cricket</label>
<input type="checkbox" id="football" name="football" value="football"/>
<label for="football">Football</label>
<input type="checkbox" id="hockey" name="hockey" value="hockey"/>
<label for="hockey">Hockey</label>
</form>
54

INTRO TO JAVASCRIPT
CS380

55 CLIENT SIDE SCRIPTING


CS380

56 WHY USE CLIENT-SIDE PROGRAMMING?

PHP already allows us to create dynamic web pages. Why also use client-
side scripting?
• client-side scripting (JavaScript) benefits:
• usability: can modify a page without having to post back to the server
(faster UI)
• efficiency: can make small, quick changes to page without waiting for
server
• event-driven: can respond to user actions like clicks and key presses
CS380

57 WHY USE CLIENT-SIDE PROGRAMMING?

• server-side programming (PHP) benefits:


• security: has access to server's private data; client can't see source code
• compatibility: not subject to browser compatibility issues
• power: can write files, open connections to servers, connect to
databases, ...
CS380

58 WHAT IS JAVASCRIPT?

• a lightweight programming language ("scripting language")


• used to make web pages interactive
• insert dynamic text into HTML (ex: user name)
• react to events (ex: page load user click)
• get information about a user's computer (ex: browser type)
• perform calculations on user's computer (ex: form validation)
CS380

59 WHAT IS JAVASCRIPT?

• a web standard (but not supported identically by all browsers)


• NOT related to Java other than by name and some syntactic similarities
CS380

60 JAVASCRIPT VS JAVA

• interpreted, not compiled


• more relaxed syntax and rules
• fewer and "looser" data types
• variables don't need to be declared
• errors often silent (few exceptions)

• key construct is the function rather than the class


• "first-class" functions are used in many situations

• contained within a web page and integrates with its HTML/CSS content
CS380

61 JAVASCRIPT VS JAVA

+ =
CS380

62 JAVASCRIPT VS. PHP

• similarities:
• both are interpreted, not compiled
• both are relaxed about syntax, rules, and types
• both are case-sensitive
• both have built-in regular expressions for
powerful text processing
CS380

63 JAVASCRIPT VS. PHP

• differences:
• JS is more object-oriented: noun.verb(), less procedural:
verb(noun)
• JS focuses on user interfaces and interacting with a document;
PHP is geared toward HTML output and file/form processing
• JS code runs on the client's browser; PHP code runs on the
web server

JS <3
CS380

64 LINKING TO A JAVASCRIPT FILE: SCRIPT


<script src="filename" type="text/javascript"></script>

HTML
• script tag should be placed in HTML page's head
• script code is stored in a separate .js file
• JS code can be placed directly in the HTML file's body or head (like CSS)
• but this is bad style (should separate content, presentation, and behavior
CS380

65 EVENT-DRIVEN PROGRAMMING

 split breaks apart a string into an array


using a delimiter
 can also be used with regular expressions
(seen later)
 join merges an array into a single string,
placing a delimiter between them
CS380

66 A JAVASCRIPT STATEMENT: ALERT


alert("IE6 detected. Suck-mode enabled.");
JS

• a JS command that pops up a dialog box with a message


CS380

67 EVENT-DRIVEN PROGRAMMING

 you are used to programs start with a


main method (or implicit main like in
PHP)
 JavaScript programs instead wait for user
actions called events and respond to
them
 event-driven programming: writing
programs driven by user events
 Let's write a page with a clickable button
that pops up a "Hello, World" window...
CS380

68 BUTTONS
<button>Click me!</button> HTML

• button's text appears inside tag; can also contain images


• To make a responsive button or other UI control:
1. choose the control (e.g. button) and event (e.g. mouse 1. click) of interest
2. write a JavaScript function to run when the event occurs
3. attach the function to the event on the control
CS380

69 JAVASCRIPT FUNCTIONS
function name() {
statement ;
statement ;
...
statement ;
} JS
function myFunction() {
alert("Hello!");
alert("How are you?");
} JS
 the above could be the contents of
example.js linked to our HTML page
 statements placed into functions can be
evaluated in response to user events
CS380

70 EVENT HANDLERS
<element attributes onclick="function();">...

HTML
<button onclick="myFunction();">Click me!</button>

HTML
• JavaScript functions can be set as event handlers
• when you interact with the element, the function will execute

• onclick is just one of many event HTML attributes we'll use


• but popping up an alert window is disruptive and annoying
• A better user experience would be to have the message appear on the page...
71 DOCUMENT OBJECT MODEL (DOM)
• most JS code manipulates elements on an HTML page
• we can examine elements' state
• e.g. see whether a box is checked
• we can change state
• e.g. insert some new text into a div
• we can change styles
• e.g. make a paragraph red
72 DOM ELEMENT OBJECTS
CS380

73 ACCESSING ELEMENTS:
DOCUMENT.GETELEMENTBYID
var name = document.getElementById("id");

JS
<button onclick="changeText();">Click me!</button>
<span id="output">replace me</span>
<input id="textbox" type="text" />
HTML
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");

textbox.style.color = "red";

}
JS
CS380

74 ACCESSING ELEMENTS:
DOCUMENT.GETELEMENTBYID
 document.getElementById returns the
DOM object for an element with a given
id
 can change the text inside most
elements by setting the innerHTML
property
 can change the text in form controls by
setting the value property
CS380

75 CHANGING ELEMENT STYLE:


ELEMENT.STYLE
Property or style
Attribute
object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
CS380

76 PREETIFY

function changeText() {
//grab or initialize text here

// font styles added by JS:


text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
text.style.color = "red"; // or pink?
}
JS
CS380

77

MORE JAVASCRIPT SYNTAX


CS380

78 VARIABLES
var name = expression; JS

var clientName = "Connie Client";


var age = 32;
var weight = 127.4; JS
• variables are declared with the var keyword (case sensitive)
• types are not specified, but JS does have types ("loosely typed")
• Number, Boolean, String, Array, Object, Function, Null, Undefined
• can find out a variable's type by calling typeof
CS380

79 NUMBER TYPE
var enrollment = 99;
var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS

• integers and real numbers are the same type (no int vs. double)
• same operators: + - * / % ++ -- = += -= *= /= %=
• similar precedence to Java
• many operators auto-convert types: "2" * 3 is 6
CS380

80 COMMENTS (SAME AS JAVA)


// single-line comment
/* multi-line comment */
JS

• identical to Java's comment syntax


• recall: 4 comment syntaxes
• HTML: <!-- comment -->
• CSS/JS/PHP: /* comment */
• Java/JS/PHP: // comment
• PHP: # comment
CS380

81 MATH OBJECT
var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);
JS

 methods: abs, ceil, cos, floor, log,


max, min, pow, random, round, sin,
sqrt, tan
 properties: E, PI
CS380

82 SPECIAL VALUES: NULL AND UNDEFINED


var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS

 undefined : has not been declared, does


not exist
 null : exists, but was specifically
assigned an empty or null value
 Why does JavaScript have both of these?
CS380

83 LOGICAL OPERATORS

 > < >= <= && || ! == != === !==


 most logical operators automatically
convert types:
 5 < "7" is true
 42 == 42.0 is true
 "5.0" == 5 is true
 === and !== are strict equality tests;
checks both type and value
 "5.0" === 5 is false
CS380

84 IF/ELSE STATEMENT (SAME AS JAVA)


if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
 identical structure to Java's if/else
statement
 JavaScript allows almost anything as a
condition
CS380

85 BOOLEAN TYPE
var iLike190M = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS
 any value can be used as a Boolean
 "falsey" values: 0, 0.0, NaN, "", null, and
undefined
 "truthy" values: anything else
 converting a value into a Boolean
explicitly:
 var boolValue = Boolean(otherValue);
 var boolValue = !!(otherValue);
CS380

86 FOR LOOP (SAME AS JAVA)


var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"
JS
CS380

87 WHILE LOOPS (SAME AS JAVA)


while (condition) {
statements;
} JS

do {
statements;
} while (condition);
JS

 break and continue keywords also


behave as in Java
CS380

88 POPUP BOXES
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
CS380

89 ARRAYS
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS

var ducks = ["Huey", "Dewey", "Louie"];


var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is 1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is 5
stooges[4] = "Shemp"; // stooges.length is 5
JS
90 ARRAY METHODS
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
JS
 array serves as many data structures: list,
queue, stack, ...
 methods: concat, join, pop, push, reverse,
shift, slice, sort, splice, toString, unshift
 push and pop add / remove from back
 unshift and shift add / remove from front
 shift and pop return the element that is
removed
91 STRING TYPE
var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" ")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
JS
• methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf, replace, split, substring, toLowerCase,
toUpperCase
• charAt returns a one-letter String (there is no char type)

• length property (not a method as in Java)


• Strings can be specified with "" or ''
• concatenation with + :
• 1 + 1 is 2, but "1" + 1 is "11"
CS380

92 MORE ABOUT STRING


 escape sequences behave as in Java: \' \"
\& \n \t \\
 converting between numbers and
var Strings:
count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah
ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN JS

• accessing the letters of a String:


var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
var lastLetter = s.charAt(s.length - 1);
JS
93 SPLITTING STRINGS: SPLIT AND JOIN
var s = "the quick brown fox";
var a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
JS

 split breaks apart a string into an array


using a delimiter
 can also be used with regular expressions
(seen later)
 join merges an array into a single string,
placing a delimiter between them

You might also like