0% found this document useful (0 votes)
62 views3 pages

Java Script Basics 3

The document describes how to add interactivity to a website using JavaScript functions and event handlers. It explains how to define functions that take arguments, and how to attach event handlers to elements using addEventListener(). It then provides examples of adding image swapping and personalized greetings functionality to a sample website on click events.

Uploaded by

Rog Don
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
62 views3 pages

Java Script Basics 3

The document describes how to add interactivity to a website using JavaScript functions and event handlers. It explains how to define functions that take arguments, and how to attach event handlers to elements using addEventListener(). It then provides examples of adding image swapping and personalized greetings functionality to a sample website on click events.

Uploaded by

Rog Don
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 3

These functions, document.querySelector and alert, are built into the browser.

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

let myHTML = document.querySelector('html');


myHTML.addEventListener('click', function() {
alert('Ouch! Stop poking me!');
});

It's just shorter.


The functions we just passed to addEventListener() here are called anonymous
functions, because they don't have a name. There's an alternative way of writing
anonymous functions, which we call an arrow function. An arrow function uses () =>
instead of function ():

document.querySelector('html').addEventListener('click', () => {
alert('Ouch! Stop poking me!');
});

Supercharging our example website

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.

let myImage = document.querySelector('img');

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:

The code retrieves the value of the image's src attribute.


The code uses a conditional to check if the src value is equal to the path of
the original image:
If it is, the code changes the src value to the path of the second image,
forcing the other image to be loaded inside the <img> element.
If it isn't (meaning it must already have changed), the src value swaps
back to the original image path, to the original state.

Adding a personalized welcome message


Next, let's change the page title to a personalized welcome message when the user
first visits the site. This welcome message will persist. Should the user leave the
site and return later, we will save the message using the Web Storage API. We will
also include an option to change the user, and therefore, the welcome message.

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:

let myButton = document.querySelector('button');


let myHeading = document.querySelector('h1');

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;
}

The setUserName() function contains a prompt() function, which displays a dialog


box, similar to alert(). This prompt() function does more than alert(), asking the
user to enter data, and storing it in a variable after the user clicks OK. In this
case, we are asking the user to enter a name. Next, the code calls on an API
localStorage, which allows us to store data in the browser and retrieve it later.
We use localStorage's setItem() function to create and store a data item called
'name', setting its value to the myName variable which contains the user's entry
for the name. Finally, we set the textContent of the heading to a string, plus the
user's newly stored name.
Add the if ... else block (below). We could call this initialization code, as it
structures the app when it first loads.

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.

You might also like