Building up some working JS

Basic practical web design Lesson 7

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.

  1. 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?
  2. Put a class attribute on your image (or one of your images, if you have more than one.) Give it a value of imgSwap.
  3. 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');
        }
    };
  4. Replace the obvious placeholders with your image web addresses. Now when you click the image, it should change to the other one!
  5. 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.

  1. Retrieves the value of the image's src attribute.
  2. Uses a conditional to check whether the src attribute value is equal to the web address of the original image:
    1. If it is, changes the src attribute value to the web address of the 2nd image, so it is loaded inside the <img> element.
    2. 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.

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.

  1. Somewhere sensible inside the JSBin HTML pane (just before the first </div> tag would be good), add the following line:
    <button>Change user</button>
  2. 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');
  3. 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:
    function setUserName() {
      var myName = prompt('Please enter your name.');
      localStorage.setItem('name', myName);
      myHeading.innerHTML = 'Hello, ' + myName + '!';
    }
    This function contains a 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 called localStorage, which allows us to store data in the browser, and retrieve it later on. We use localStorage's setItem() function to create and store a data item called 'name', and make its value equal to the myName variable that contains the name the user entered. Finally, we set the innerHTML 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.
  4. 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:
    if(!localStorage.getItem('name')) {
      setUserName();
    } else {
      var storedName = localStorage.getItem('name');
      myHeading.innerHTML = 'Hello, ' + storedName + '!';
    }
    This block first uses the negation operator (! — logical NOT) to check whether the name data item exists — if it doesn't exist, the setUserName() 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 the getItem() function and set the innerHTML of the heading the same as we did inside setUserName(), except the name is taken from localStorage, not the prompt dialog box the user fills in.
  5. Finally, add the following code below everything else. Here we put an onclick event handler on the button, so that when it's clicked the setUserName() 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:


Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License. Share it, make it better, use it for good.