Why JavaScript?
Javascript allows you to make your pages interactive. You can use it to build
anything from a simple animation to a giant web application like Twitter
or GitHub. It gives you total control to add, remove, or modify content you've
made with HTML. You can also use it to change styles and add or remove
classes.
Writing JavaScript in a web page can be tricky, because you don't start with a
blank slate. All of the contents of the web browser, including built-in browser
objects and your own HTML elements, are there too. You just have to figure out
how to get to them with JavaScript so you can manipulate them.
What Did That Script Do?
We'll go through it line by line:
The first line declares a function
, a bit a of reusable code you can refer
to later by calling its name:
function replaceName() {
The next two lines are the steps the function will do. The first one creates
a variable called myNewName
and sets it equal to a value. The browser window
will try to get this value using its prompt
method, a built-in function it
knows how to do, that involves popping up a text box for you to fill in.
var myNewName = window.prompt('Pick a new name!');
In the next line it goes into your HTML document and uses getElementById
, a built-in function it knows to do, to locate your user-name
span. It then sets the span's HTML contents to the value of the variable myNewName
.
document.getElementById('user-name').innerHTML = myNewName;
}
closes the replaceName
function you started defining in the first line.
The final line tells the browser, 'When I click the document, run the function called replaceName
.
document.onclick = replaceName;
Some elements of this script, like 'document.onclick' or the '.innerHTML' property, are a little out of date. They're great ways to start playing with Javascript, but when you write your own pro Javascript, you may want to use more contemporary techniques or a library like jQuery that will do these things for you in a less clunky way.