Javascript Overview

Download Report

Transcript Javascript Overview

Javascript Overview
What is Javascript?
• May be one of the most popular programming
languages ever
• Runs in the browser, not on the server
• All modern browsers support javascript
• Easy to learn
• Is NOT Java; completely different in concept
and design
What Can You Do?
• Change html content
http://www.w3schools.com/js/tryit.asp?filename=tr
yjs_intro_inner_html
• Change html attributes
http://www.w3schools.com/js/tryit.asp?filename=tr
yjs_intro_lightbulb
• Validate data in the browser
http://www.w3schools.com/js/tryit.asp?filename=tr
yjs_intro_validate
Where to place Javascript
• Can be placed in the body OR head; best to put in
a separate .js file. Keep your javascript all in one
place
• In html code, must put between <script></script>
tags
<script>
document.getElementById("demo").innerHT
ML = "My First JavaScript";
</script>
Head and Body Examples
• Head Example:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_
whereto_head
• Body Example:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_
whereto_body
• External File:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_
whereto_external
External File Advantages
• Separates html and code
• Makes html and Javascript easier to read and
maintain
• Cached Javacript files can speed up page loads
Display Possibilities
•
•
•
•
Write to an alert box using window.alert()
Write to html output using document.write()
Write to an html element using innerHTML
Write into the browser console using
console.log()
Using innerHTML
• Use the document.getElementById(id)
method.
– Remember when we covered the DOM?
• The id attribute defines the html element; the
innerHTML property defines the html content
http://www.w3schools.com/js/tryit.asp?filename=tr
yjs_output_dom
Language Syntax, Statements,
Variables, Operators, Datatypes
http://www.w3schools.com/js/js_syntax.asp
Functions
• A block of code designed to perform a particular task
• Executed when something invokes it
• Defined bwith the function keyword, followed by a
name, followed by parentheses()
• The parentheses may include parameter names
followed by commas: (parameter1, parameter2)
• The code to be executed is included in {}
• The functions often compute a return value, which can
be returned to the caller
http://www.w3schools.com/js/tryit.asp?filename=tryjs_funct
ion_return
Objects
• Objects are variables too but can contain
many values and functions
http://www.w3schools.com/js/js_objects.asp
Events
• Things that happen to html elements (i.e., the
browser initiates or the user initiates)
• Javascript can “react” to on these events to do
something you want done
• Html allows event handler attributes, with
javascript code, to be added to html elements
• <some-HTML-element some-event="some
JavaScript">
http://www.w3schools.com/js/tryit.asp?filename=tryjs_event_
onclick1