Intro to HTML, CSS and JavaScript Part 3: JavaScript

 

 

So far you should know how to add html elements to a document and set their properties using a separate style sheet.   In this tutorial you will see how to use JavaScript to listen for events and add some more interesting functionality.

 

Again, for more in-depth information check out the tutorials on www.w3schools.com.  

 

 

Background:

JavaScript was invented in 1995 and has since become the most popular programming language in the world.  It gets embedded into html and runs in the web browser on the user’s computer, phone or tablet.  A single html page can have several scripts running in it. 

 

Below I explain how to use JavaScript to:

·        Change the text of the html document

·        Call functions on button click

 

 

But it can do so much more.  Seriously, go through the w3 tutorials yourself. J

 

 

 

Changing html From Java Script

 

 

<!DOCTYPE html>

 

<html>

<body>

<h1>JavaScript Demo</h1>

 

<p id="changeMe"></p>

 

<script>

     document.getElementById("changeMe").innerHTML ="hello world";

</script>

 

 

 

</body>

</html>

This example shows how you can use the getElementById() function.

It works by changing the element called changeMe to the text “Hello World”.

 

This is how you can display the results of any calculations you do, or display status updates on the screen.

 

Note: It is important to put the variable above the script. Otherwise the script can’t see it and nothing will happen.  

Functions From Buttons

 

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Demo</h1>

 

<script>

     function fooFunction(){

           document.getElementById("changeMe").innerHTML ="hello world";

 

     }

</script>

 

<button onclick="fooFunction()">Click Me</button>

 

<p id="changeMe"></p>

 

</body>

</html>

When the “click me” button is pressed,  fooFunction() is called.  fooFunciton then changes the changeMe element in the html page to “Hello World”

Try This

 

Add a script to your demo program so that an appropriate message pops up on the screen when the buttons are pressed.