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

Complex Webpages use JavaScript and jQuery

This post will explain exactly how to use JavaScript and jQuery to put content from objects into the structure of a template.

JavaScript objects and HTML templates allow you to separate content from structure. This technique will allow you to make powerful and complex webpages. You put these two things together using JavaScript and jQuery.

The first step is to use jQuery to get the text of the template out of the DOM.

var source = $(“#image-template”).html();

 

Next, you have to compile the template. You call the Handlebars.compile function and pass in the source text you got from the template, and the result is a variable called template. The variable template is a JavaScript function that turns objects into HTML.

var template = Handlebars.compile(source);

 

Now you will want to call the template function, pass in your data, and assign that to some HTML.

var html = template(data);

 

Finally, the last step is to use jQuery to copy the HTML back into your DOM element.

$(‘#Content’).html(html);

 

This above sequence of steps is what you need to do to turn your template text and content object into HTML code.

Take a look at a more complete example of how this works. First, look at all the and stylesheets you will need to bring in.

Importing Stylesheets

Inside the <body> tags you will see an empty <div>. You will soon push content inside this empty <div>. Below that is the actual template.

The HTML Template

Then at the end you will see the JavaScript. This goes through the sequence of steps that was shown at the beginning of this post.

Sequence of Steps

The last thing not pictured is the closing </script> tag. Do not forget that.

Pictured below is what the HTML page should look like. It is very simple, but the process learned in this post will allow you to make more complex webpages.

Rendered HTML

 

Separate Structure from Content

To be an efficient web developer, you need to know how to separate structure from content.

Take a look at the picture below that highlights the structure components of a webpage.

HTML Structure
The structure of the HTML is highlighted.

The next picture highlights the content.

HTML Content
The content of the HTML is highlighted.

These are the two things you should learn to separate. Knowing how to separate structure from content will create a more powerful web experience.

Why is it more powerful? Suppose you have a thousand webpages like the one pictured above. All the structure is the same, but your content is different for each page. Now, suppose you decide the <h2> is too big, and you want to change it to an <h3> tag. Well, you just created lots of work for yourself. You have lots of repetitive editing to do. However, if you separate structure from content, you will avoid this problem.

The idea is to create a template for the separate structure. This template can then be used to display as much content as you want. Therefore, if you need to change the structure, you only have to edit it once.

Python Regular Expressions

 This post should serve as a basic guide for Python regular expressions.

It is recommended to learn Python basics before you learn Python regular expressions.

Regular expressions, in general, are a language unto themselves. They can be used in many different languages. They involve cryptic, yet very succinct ways of presenting solutions to programming problems. For some, regular expressions will come very natural, but others will prefer the step-by-step method of writing code. You do not have to know regular expressions, but if you do, you may find them quite fun to work with.

Wk2_RegExpDef

You might want to bookmark a character guide for Python regular expressions.

You can see from the guide that regular expressions are a language of characters. Certain characters have a special meaning, similar to how Python reserved words have special meaning. Shown below is a module you should follow if you want to make use of Python regular expressions in your program.

Wk2_RegExpMod

Consider these two example lines of text from the mbox-short.txt file.

X-DSPAM-Result:
X-Plane is behind schedule:

Now consider the following code:

import re
lines = open(‘mbox-short.txt’)
for line in lines:
++++line = line.rstrip()
++++if re.search(‘^X.*:’):

The “if” statement will catch lines that start with (‘^’) ‘X’, followed by any character (‘.’), zero or more times (‘*’), followed by a ‘:’. The ‘X’ and ‘:’ are not special characters, the other characters do have special meaning. This if statement should catch the two example lines of text written above.

Suppose you do not want to catch a line if it has blank spaces, or whitespace (the second example line). You would modify the regular expression as follows:

for line in lines:
++++line = line.rstrip()
++++if re.search(‘^X-\S+:’):

Now your if statement will only match lines that start with ‘X-‘, followed by non-whitespace (‘\S’), one or more times (‘+’), followed by a ‘:’.

Matching and Extracting Data with Python Regular Expressions

The method “re.search()” returns a True or False, depending if the regular expression finds a match.

Use “re.findall()” if you want matching strings to be extracted.

Consider these four lines of code below, in the Python interpreter.

Wk2_RegExpMatchExtract

The ‘[0-9]+’ represents any single digit that occurs one or more times. Therefore, the variable ‘y’ returns a Python list of matches from the parameter, which is ‘x’. So, “re.findall()” extracts matching data and returns a list.

It is important to know that matching regular expressions will return the largest possible string, by default. For example:

>>> import re
>>> x = ‘From: Using the : character’
>>> y = re.findall(‘^F.+:’, x)
>>> print y
[‘From: Using the :’]

Did you notice? The “re.findall()” did not stop at ‘From:’, because that is not the largest possible matching string. This concept is referred to as greedy matching, because it returns the largest possible match. If you wanted to stop at the first colon, then you would need to use non-greedy matching:

>>> y = re.findall(‘^F.+?:’, x)

This regular expression will return the shortest string match.

Bootstrap Themes – Free Download

The bootstrap grid system is so popular that people have created free bootstrap themes that you can use for your site. Notwithstanding, you should always check the license of your theme before you use it.

One bootstrap themes resource to start with is free bootstrap themes.

For this resource above, you can first preview the theme. If you like it, then click the download button for a link to a minified version of the code. Simply copy the code and paste it into a new bootstrap.css file, if you wish to use it on your site.

Another one you might consider is commercial bootstrap themes.

Bootstrap Grid System – Gain Control

The bootstrap grid system is a brilliant method to gain control over the responsiveness of your website. Consider the built-in bootstrap classes in the following code:

<div class=”row”> <!– start row –>

++<div class=”col-xs-6 col-md-3 col-lg-2″>
++++<img src=”.images/img_1.jpg”>
++</div>

++<div class=”col-xs-6 col-md-3 col-lg-2″>
++++<img src=”.images/img_2.jpg”>
++</div>

++<div class=”col-xs-6 col-md-3 col-lg-2″>
++++<img src=”.images/img_3.jpg”>
++</div>

++<div class=”col-xs-6 col-md-3 col-lg-2″>
++++<img src=”.images/img_4.jpg”>
++</div>

++<div class=”col-xs-6 col-md-3 col-lg-2″>
++++<img src=”.images/img_5.jpg”>
++</div>

++<div class=”col-xs-6 col-md-3 col-lg-2″>
++++<img src=”.images/img_6.jpg”>
++</div>

</div> <!– end row –>

The main thing you need to know about this example derives from the <div class=”col-xs-6 col-md-3 col-lg-2″> tag.

Remember that bootstrap is built on 12 evenly spaced grids.

The class “col-xs-6” indicates that on an extra small screen, the image will consume six of those grid spaces. Thus, you will see two columns of pictures.

The class “col-md-3” indicates that on a medium screen, the image will consume three of those grid spaces. Thus, you will see four columns of pictures.

The class “col-lg-2” indicates that on a medium screen, the image will consume two of those grid spaces. Thus, you will see six columns of pictures.

You can see how the bootstrap grid system (along with these built-in classes) allows you to easily gain control over how your content is displayed.

Plan first! So, as you build your site you will know how many of the grid spaces to consume on an extra small, medium, or large screen size.

Read the documentation on the bootstrap grid system, for more information.

How to Leave a Breadcrumb Trail

A good site should communicate to the users where they are on your site, at all times. A typical way to telling users where they are is to leave a breadcrumb trail on all your pages.

To build a bootstrap navigation bar, you use an unordered list, <ul>. For a bootstrap breadcrumb trail, you will us an ordered list, <ol>. This makes sense. Order is not so important for the navbar, but it is important for the breadcrumb trail. You want users to know where they are, and how to get back to where they came from.

For example, directly under the main heading, <h1>, on a page called “Albums”, you would create a breadcrumb trail as follows:

<!– start breadcrumb –>
<ol class=”breadcrumb”>
++<li><a href=”index.html”>Home</a></li>
++<li><a href=”albums.html”>Albums</a></li>
</ol>
<!– end breadcrumb –>

Using the bootstrap class “breadcrumb”, the trail on your albums page should display as pictured.

bootstrap breadcrumb trail

You would then add <li> elements to your breadcrumb trail depending on how many levels deep you go into your website. For example if someone clicks on one of your albums, then it would take that user to the photos page. Therefore, you would add a third <li> element to the breadcrumb on the photos page.

It is suggested to read the bootstrap documentation on breadcrumb trails, for more information.

Build Out Your Site

This lesson will take a look at how to build out a website. The site will be an image gallery, where you navigate to various photo albums, and then view individual photos in the albums.

Use the code from the lesson where you build the un-collapsed navigation bar, and modify it as follows:

<!– start un-collapsed navbar –>
<div class=”collapse navbar-collapse” id=”main_navbar”>
++<ul class=”nav navbar-nav”>
++++<li class=”active”><a href=”index.html”>Home</a></li>
++++<li><a href=”albums.html”>Albums</a></li>
++++<li><a href=”photos.html”>Photos</a></li>
++ </div>
<!– stop un-collapsed navbar –>

 

Files for WebsiteNow your navbar has links for the home, albums, and photos. Also, the href attribute specifies the correct file name for these pages, but you have not made those pages yet. That is the next thing to do. Simply make copies of our index.html file, and change the name of each copy respectively. Your website folder should contain the files as shown.

The photo1.html page was also added, because this is where you will show individual photos. However, it will not be in the navbar.

Now you can add photos to your albums page. Place the photos under the closing </nav> tag.

<div class=”container”>
++<h1>Photo Albums</h1>
++++<a href=”photos.html”><img class=”album_cover” src=”./images/img_1.jpg” alt=”graffiti image”></a>
++++<a href=”photos.html”><img class=”album_cover” src=”./images/img_2.jpg” alt=”english breakfast”></a>
++++<a href=”photos.html”><img class=”album_cover” src=”./images/img_3.jpg” alt=”lots of cheese”></a>
</div>

Notice each image links to the photos.html page.

The class “album_cover” will resize the picture, but you will need to add a styles.css sheet and use the following code:

.album_cover {
++++width: 25%;
++++border: 5px solid black;
}

Make sure you add <link href=”css/styles.css” rel=”stylesheet”> to your all your new html pages!

This resizes the photo with CSS3. The other option would have been to use a photo editor to make thumbnail size photos, and use thumbnails for your album covers. On a small mobile device, your albums page should now look like the photo shown below.

Wk2Albums

Add Pictures to the Photo Page

Now you can add pictures to your photos.html page. Use the code shown below.

<div class=”container”>
++<h1>Photos</h1>
++++<a href=”photo1.html”><img class=”photo_list” src=”./images/img_1.jpg” alt=”graffiti image”></a>
++++<img class=”photo_list” src=”./images/img_2.jpg” alt=”english breakfast”>
++++<img class=”photo_list” src=”./images/img_3.jpg” alt=”lots of cheese”>
</div>

Notice the href for the <a> tag links to the photo1 page. This allows the user to view a larger size of the image.

The CSS3 for the class “photo_list” can be:

.photo_list {
++++width: 25%;
}

It does not make sense that our photos page is just a list of the same photos of the album cover page, but this example is just for demonstrative purposes. you can add your own distinct photos, and your photo pages for each album. However, you can use the code in this example to guide you.

Finally, add the appropriate image to your photo1.html page.

<div class=”container”>
++<h1>Graffiti Photo</h1>
++++<img class=”single_photo” src=”./images/img_1.jpg” alt=”graffiti image”></a>
</div>

The CSS3 for the “single_photo” class can be:

.single_photo {
++++width: 75%
}

This code in the stylesheet will display a larger version of the image.

 

Collapsible Navigation Bar – A Must for Mobile Friendly

After you learn how to build a basic bootstrap navigation bar, you will want to know how to transform it to a collapsible navigation bar. Why? Well, if the user is on a small mobile device, then the navigation bar may consume the entire screen. This would result in a bad user experience, and the user may quickly leave your site. If you build a collapsible navigation bar, then the user experience is improved.

In order to build a collapsible navigation bar, you will need to program your site so it knows what to display when the nav bar is collapsed, and when it is not collapsed.

Start with your basic nav bar code from the previous lesson, and build on it to add the code necessary to build a collapsible navigation bar.

The correct code is shown below. Directly below are descriptions of all the additions shown in the code.

Collapsible Nav Bar Code
HTML5 Code for a Collapsible Navigation Bar

An Analysis of the Collapsible Navigation Bar Code

Make another <div> element for the collapsed navbar. Label it with comments, so you can distinguish the nav bars.

Add the built-in bootstrap class “navbar-header” to the collapsed navbar. This class tells your page that the collapsed navbar should sit on top of everything else.

Add the “collapse navbar-collapse” class to your un-collapsed ‘div’ element.

The next step is to make a make the <button> in your collapsed ‘div’ interact with your un-collapsed <div>. So, set a “main_navbar” id inside your un-collapsed <div>.

Now you will add a whole slew of characteristics to your button. Look above at all the characteristics added to the <button> tag. The type given improves accessibility. The class tells what to show when the navbar is collapsed. The data-toggle is picked up by bootstrap.js to give the button interactivity. The data-target specifies what actually collapses (it’s the main navbar). Finally, aria-expanded implies the button will not initially be seen.

Take a look at your progress. The images below show how the nav bar appears, collapsed and un-collapsed, on a small screen.

Wk2NavBarCollapsedWk2NavBarUnCollapsed

Navigation Bar – Build It Bootstrap Style

Letting users know where they can go on a website is commonly done with a navigation bar. Bootstrap has lots of functionality for making a navigation bar.

Code for a  navigation bar typically starts directly below the HTML <body> tag. The following code could be used as a starting template for a bootstrap navigation bar:


<nav class="navbar navbar-default">
++<div class="container-fluid">
++++++<ul class="nav navbar-nav">
++++++++<li class="active"><a href="#">Home</a></li>
++++++++<li><a href="#">Photos</a></li>
++++++</ul>
++</div>
</nav>

 

  • The <nav> tag is important because it will alert screen readers that the user is on a navbar. This would be important for visually impaired users.
  • The “navbar navbar-default” and “nav navbar-nav” classes separate this element from other elements on the page so that it actually looks like a navigation bar (rather than a unordered list).
  • Finally, the “active” class gives an indication telling the users where they are on your website.
  • The “container-fluid” class offers full functionality across different browsers and screen sizes.