JavaScript Combines Structure and Content

This post will focus on how JavaScript combines structure and content.

JavaScript integrates content and structure for web pages to create a dynamic user experience. You use arrays to store content, and you use templates to define structure. JavaScript combines the two.

If you have an image gallery, and you click on one of the photo albums, you need write code that remembers what the currently selected album is. This is important because if the user clicks on slide show, you want to show a slide show of the currently selected album.

Wk4SwitchDisplay1

In this case, you can create a gallery.js file. This will contain all the code that maps content data to the templates. This code needs to know what to display, and when to display it.

Wk4SwitchDisplay2

Look at the above picture. The first thing you see are a bunch of variables. These variables represent the templates. Here, you compile them at the beginning, so they can be used later. You also see variables for the current album and current photo.

The function show template is going to take a template, apply data to it, and display it to the HTML. This process is encapsulated into a single function so it can be easily reused.

A very important rule for large, dynamic sites, is you want all the page to load before you run any JavaScript. This is the purpose of the function $(document).ready, which calls an anonymous function. The anonymous function contains everything you need to make your website work.

You start by loading and compiling all your templates. You have your templates saved as variables, so you can easily call them later.

Next you will have click functions for your albums, photos, and slide show tabs. These are the three main tabs on your web page. Clicking each of those tabs will cause a distinct template to be loaded.

Wk4SwitchDisplay3

Later down in the code you want to grab all the elements with the class “album-thumbnail”, and give them a click function. You grab the data id and use that to select the correct album out of the array, and then show that album by the photos template. You also save it in the variable current_album. Again, it is important for your code to know what the current album is. The last thing is some code showing what to display when you click on a photo thumbnail.

Wk4SwitchDisplay4

Leave a Reply

Your email address will not be published. Required fields are marked *