JavaScript Introduction

JavaScript can update and change both HTML/CSS

It can calculate, manipulate and validate data

JavaScript Can Change HTML Content

One of many js HTML methods is getElementById()

The example below "finds" an HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello JavaScript":

JavaScript can change HTML content.

	<p id="demo">JavaScript can change HTML content.</p>

	<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>

Toggle a lightbulb on and off

See

JavaScript can change the style of an HTML element.

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

	<button type="button" onclick="document.getElementById('demo1').style.fontSize='35px'">Click Me!</button>

JavaScript can hide and unhide HTML elements.

	<p id="demo">JavaScript can hide HTML elements.</p>

	<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>

JavaScript writing

In HTML, js code is inserted between <script> and </script> tags

NOTE: Old JavaScript examples may use a type attribute: <script type="text/javascript">

The type attribute is not required. JavaScript is the default scripting language in HTML.

JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.

JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the , or in the section of an HTML page, or in both

JavaScript in

In this example, a JavaScript function is placed in the section of an HTML page.

The function is invoked (called) when a button is clicked:

	<!DOCTYPE html>
	<html>
	<head>
	<script>
	function myFunction() {
	  document.getElementById("demo").innerHTML = "Paragraph changed.";
	}
	</script>
	</head>
	<body>
	<h2>Demo JavaScript in Head</h2>

	<p id="demo">A Paragraph</p>
	<button type="button" onclick="myFunction()">Try it</button>

	</body>
	</html>

NOTE: Placing scripts at the bottom of the element improves the display speed, because script interpretation slows down the display.

External JavaScript

<script src="myScript.js"></script>

You can place an external script reference in <head> or <body> as you like.

External scripts cannot contain <script> tags