JavaScript – Basics Summary • Chrome: Inspect Element

advertisement
JavaScript – Basics Summary
• Chrome: Inspect Element ->Console
• Firefox: Tools->Web Developer-> Web Console
JavaScript code can add dynamic information to a web page
that static HTML code cannot.
Put JavaScript code in <script> </script> tags.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A First JavaScript Program</title>
<script>
document.write("<h1>Welcome to JavaScript
programming!</h1>");
</script>
</head>
<body>
</body>
</html>
JavaScript can occur in the head or the body of the code.
I Declaring a variable / Scope concerns
var
Declare a variable
var carname;
Assign a variable:
carname="Volvo";
The var keyword is never "needed". However if you don't use it then
the variable that you are declaring will be exposed in the global scope.
Usually this is not what you want. Usually you only want your variable
to be visible in the current scope.
Example:
for(var i=0; i< array.length; i++){
//do something
}
Or:
var i;
for(i=0; i< array.length; i++){
//do something
}
Doing it like this:
for(i=0; i< array.length; i++){
//do something
}
..will create a variable called i in the global scope. If someone else
happened to also be using a global i variable, then you've just
overwritten their variable.
Example 1:
var a = "A"
function testScope(){
var a = "B"
alert(a) //B
}
alert(a); //A
Example 2:
var a = "A";
function testVar(){
a = "B"
alert(a) //B
}
alert(a) //B
parseInt
converts its string argument to an integer
Also parseFloat, etc.
• With the object model JavaScript can:
– Change, add, or remove all the HTML elements and
attributes in the page
– Change all the CSS styles in the page
Example:
<body>
<p id="intro">Hello World!</p>
<script>
txt=document.getElementById("intro").innerHTML;
document.write(txt);
</script>
</body>
JavaScript Shiv and CSS Workaround:
Older browsers ignore the HTML5 semantic elements.
<head>
<!--[if lt IE 9]>
<script
src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
The above javascript code adds new elements (aside, figure, etc)
CSS workaround – in the CSS include:
article, aside, figure, footer, header, hgroup, menu, nav, section
{ display: block; }
Download