Supercharging our example website
Now we've reviewed a few basics of JavaScript, let's add a couple of cool basic features to our example site to give you some first steps into what is possible.
Before starting this section, delete everything you've got at the moment in your JSBin JavaScript pane.
Adding an image changer
In this section we'll add another image to our site, and add some simple JavaScript to change between the two when the image is clicked on.
- First of all, find another image that you'd like to feature on your site. via Google Images. Open it in a new tab, find another image, and save the web address of the image in a safe place for now; why not just leave it in the tab you opened Google Images in for now?
- Put a class attribute on your image (or one of your images, if you have more than one.) Give it a value of
imgSwap
. - Go to your JavaScript pane, and enter the following JavaScript (delete anything that's already there):
var myImage = document.querySelector('.imgSwap'); myImage.onclick = function() { var mySrc = myImage.getAttribute('src'); if(mySrc === 'YOUR FIRST IMAGE WEB ADDRESS') { myImage.setAttribute('src','YOUR SECOND IMAGE WEB ADDRESS'); } else { myImage.setAttribute('src','YOUR FIRST IMAGE WEB ADDRESS'); } };
- Replace the obvious placeholders with your image web addresses. Now when you click the image, it should change to the other one!
Note: If the example doesn't work, you might want to try a different image. Some people don't like you linking to their images!
So here, we are storing a reference to our image element in the myImage
variable. Next, we make this variable's onclick
event handler property equal to an anonymous function containing code that does the following every time the image is clicked.
- Retrieves the value of the image's
src
attribute. - Uses a conditional to check whether the
src
attribute value is equal to the web address of the original image:- If it is, changes the
src
attribute value to the web address of the 2nd image, so it is loaded inside the<img>
element. - If it isn't (meaning it must already have changed), changes the
src
value back to the original image's web address, to flip it back to what it was originally.
- If it is, changes the
Adding a personalized welcome message
Next we will add another bit of code, to change the page's title to include a personalized welcome message when the user first navigates to the site. This welcome message will persist when the user leaves the site and then comes back. We will also include an option to change the user and therefore the welcome message anytime it is required.
- Somewhere sensible inside the JSBin HTML pane (just before the first
</div>
tag would be good), add the following line:<button>Change user</button>
- Add the following code at the bottom of the JavaScript pane, exactly as written — this grabs references to the new button we added and the heading, and stores them in variables:
var myButton = document.querySelector('button'); var myHeading = document.querySelector('h1');
- Now add the following function (again at the bottom of the JavaScript pane) to set the personalized greeting — this won't do anything yet, but we'll use it later on:
This function contains afunction setUserName() { var myName = prompt('Please enter your name.'); localStorage.setItem('name', myName); myHeading.innerHTML = 'Hello, ' + myName + '!'; }
prompt()
function, which asks the user to enter some data and stores that data in a variable when the dialog OK button is pressed. In this case, we are asking the user to enter their name. Next, we call on an API calledlocalStorage
, which allows us to store data in the browser, and retrieve it later on. We use localStorage'ssetItem()
function to create and store a data item called'name'
, and make its value equal to themyName
variable that contains the name the user entered. Finally, we set theinnerHTML
property of the heading (representing the text inside the element) to a string containing'Hello, '
, with the user name and an exclamation mark glued onto the end of it. - Below everything else, add this
if ... else
block — we could call this the initialization code, as it sets up the app when it first loads:
This block first uses the negation operator (if(!localStorage.getItem('name')) { setUserName(); } else { var storedName = localStorage.getItem('name'); myHeading.innerHTML = 'Hello, ' + storedName + '!'; }
!
— logical NOT) to check whether thename
data item exists — if it doesn't exist, thesetUserName()
function is run to create it. If it already exists (i.e. the user set it when they previously visited the site), we retrieve the stored name using thegetItem()
function and set theinnerHTML
of the heading the same as we did insidesetUserName()
, except the name is taken from localStorage, not the prompt dialog box the user fills in. - Finally, add the following code below everything else. Here we put an
onclick
event handler on the button, so that when it's clicked thesetUserName()
function is run. This allows the user to set a new name whenever they want by pressing the button:myButton.onclick = function() { setUserName(); };
The web page will first ask you for your user name then give you a personalized message. You can then change the name any time you like by pressing the button. As an added bonus, because the name is stored inside localStorage, it persists after the site is closed down, so the personalized message will still be there when you open the site up again!
See my finished page for reference.
Where next?
If you enjoyed this course and would like to learn more, I'd suggest you try one of the following:
- Getting started with the Web: A useful guide that covers the basics of file structures for a real web site, publishing your site online, and also aspects of HTML/CSS/JavaScript. Work through this one first.
- Codecademy: Small, repetitive bite size lessons on JavaScript, HTML/CSS, and other programming languages. Really useful for learning.
- A Practical Guide to HTML and CSS, by Shay Howe: Shay is a great teacher, and this course is very useful, although it is a bit more involved.
- Khan academy: A large amount of learning material on many subjects, not just programming.