Java Script Basics 3
Java Script Basics 3
If you see something which looks like a variable name, but it's followed by
parentheses— () —it is likely a function. Functions often take arguments: bits of
data they need to do their job. Arguments go inside the parentheses, separated by
commas if there is more than one argument.
For example, the alert() function makes a pop-up box appear inside the browser
window, but we need to give it a string as an argument to tell the function what
message to display.
You can also define your own functions. In the next example, we create a simple
function which takes two numbers as arguments and multiplies them:
function multiply(num1,num2) {
let result = num1 * num2;
return result;
}
Try running this in the console; then test with several arguments. For example:
multiply(4, 7);
multiply(20, 20);
multiply(0.5, 3);
Note: The return statement tells the browser to return the result variable out of
the function so it is available to use. This is necessary because variables defined
inside functions are only available inside those functions. This is called variable
scoping. (Read more about variable scoping.)
Events
Real interactivity on a website requires event handlers. These are code structures
that listen for activity in the browser, and run code in response. The most obvious
example is handling the click event, which is fired by the browser when you click
on something with your mouse. To demonstrate this, enter the following into your
console, then click on the current webpage:
document.querySelector('html').addEventListener('click', function() {
alert('Ouch! Stop poking me!');
});
There are many ways to attach an event handler to an element. Here we select the
<html> element. We then call its addEventListener() function, passing in the name
of the event to listen to ('click') and a function to run when the event happens.
Note that
document.querySelector('html').addEventListener('click', function() {
alert('Ouch! Stop poking me!');
});
is equivalent to
document.querySelector('html').addEventListener('click', () => {
alert('Ouch! Stop poking me!');
});
With this review of JavaScript basics completed (above), let's add some new
features to our example site.
Before going any further, delete the current contents of your main.js file — the
bit you added earlier during the "Hello world!" example — and save the empty file.
If you don't, the existing code will clash with the new code you are about to add.
Adding an image changer
In this section, you will learn how to use JavaScript and DOM API features to
alternate the display of one of two images. This change will happen as a user
clicks the displayed image.
Choose an image you want to feature on your example site. Ideally, the image
will be the same size as the image you added previously, or as close as possible.
Save this image in your images folder.
Rename the image firefox2.png.
Add the JavaScript below to your main.js file.
myImage.onclick = function() {
let mySrc = myImage.getAttribute('src');
if(mySrc === 'images/firefox-icon.png') {
myImage.setAttribute('src','images/firefox2.png');
} else {
myImage.setAttribute('src','images/firefox-icon.png');
}
}
Save all files and load index.html in the browser. Now when you click the
image, it should change to the other one.
This is what happened. You stored a reference to your <img> element in the myImage
variable. Next, you made this variable's onclick event handler property equal to a
function with no name (an "anonymous" function). So every time this element is
clicked:
In index.html, add the following line just before the <script> element:
<button>Change user</button>
In main.js, place the following code at the bottom of the file, exactly as it is
written. This takes references to the new button and the heading, storing each
inside variables:
Add the function below to set the personalized greeting. This won't do anything
yet, but this will change soon.
function setUserName() {
let myName = prompt('Please enter your name.');
localStorage.setItem('name', myName);
myHeading.textContent = 'Mozilla is cool, ' + myName;
}
if(!localStorage.getItem('name')) {
setUserName();
} else {
let storedName = localStorage.getItem('name');
myHeading.textContent = 'Mozilla is cool, ' + storedName;
}
This first line of this block uses the negation operator (logical NOT, represented
by the !) to check whether the name data exists. If not, the setUserName() function
runs to create it. If it exists (that is, the user set a user name during a
previous visit), we retrieve the stored name using getItem() and set the
textContent of the heading to a string, plus the user's name, as we did inside
setUserName().
Put this onclick event handler (below) on the button. When clicked, setUserName()
runs. This allows the user to enter a different name by pressing the button.