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

 

Learn Advanced JavaScript Features

If you are a budding web developer, you will need to learn advanced JavaScript features, such as changing the functionality of elements as you interact with them, and passing functions into other functions. In other words, as interacting with the web page evolves, the functionality has to evolve with it.

Breakdown the following JavaScript / jQuery to grasp this concept:

$(“#title”).click(function() {
$(“#title”).html(“Hello”);
$(“#title”).off(“.click”);
});

  • $(“#title”) grabs the element you want to work with.
  • .click changes the onclick function. This allows you to change the interactivity of onclick as your page evolves.
  • (function() passes in an anonymous function. It does not need to have a name, nor does it need arguments.

$(“#title”).html(“Hello”);
$(“#title”).off(“.click”);

  • The code above is what you see inside the curly brackets. These are the arguments of .click. This type of programming would seem very odd to someone with a background in Java, but this is an example of how JavaScript is different from Java.}); These last three pieces of syntax close the function, end the .click arguments, and end the line.

You can put this code in the context of an HTML page as follows:

<head>
<script src=”http://code.jquery.com/jquery-1.11.3.min.js”></script>
</head>

<body>
<h1 id =”title” onclick=”sayGoodbye();”>
Hello
</h1>
</body>

<script type=”text/javascript”>
function sayGoodbye() {
$(“#title”).html(“Goodbye”);
$(“#title”).click(function() {
$(“#title”).html(“Hello”);
$(“#title”).off(“click”);
});
};
</script>

So now, rather than just being able to change the text from ‘Hello’ to ‘Goodbye’, you can keep clicking on the <h1> element to switch back and forth.

While this is a simple example, it gives a nice demonstration of how the interactivity of a page can change, as the user does different things.

If you want a PHP developer job, then JavaScript would be a nice to tool to add to your skill set. It will empower you to build pages that are interactive for the user.

Complex JavaScript – Keep Code Clean

complex javascriptThere are standard coding practices to adhere to when coding more complex JavaScript. The underlying concept is to seperate JavaScript from the HTML document.

Look at this line of code for example.

<h1 id=”title” onclick=”alert(‘hello’);”>Hello</h1>

 

In this instance there is one bit of JavaScript after the onclick attribute. There certainly could be much more JavaScript after the onclick attribute, but that is considered bad form to write many lines of code for one attribute. There is a cleaner way to do it.

The <script> tag is used to import jQuery. A <script> tag is also used to call on custom code.

<script type=”text/javascript”>alert(‘Hello’);</script>

The above script has a type indicating that it is text consisting of JavaScript. Everything inside the script tags is the JavaScript.

Take one step further and put the JavaScript inside a function named sayHello().

function sayHello() {
++++alert(‘Hello’);
};

And one more step by simply placing the function inside the <script> tag.

<script type=”text/javascript”>
function sayHello() {
++++alert(‘Hello’);
};
</script>

 

This might have been lots of work for a simple JavaScript function, but consider if the function is 500 lines of JavaScript, and is easy to see why doing it this way makes sense.

Now you can look at everything in the context of a web page.

<head>
</head><body>
++<h1 id =”title” onclick=”sayHello()”>
++++Hello
++</h1>
</body>
<script type=”text/javascript”>
function sayHello() {
++++alert(‘Hello’);
};
</script>

This can be taken one step further with a separate JavaScript file. Similar to a CSS file, a JavaScript file can be used to affect multiple HTML pages.

To do this, paste all the JavaScript code in a separate file with a name like scripts.js. Do not include the <script> tags in this document. In the HTML files, simply link the JavaScript file with <script src="scripts.js"> </script>. The way JavaScript functions are invoked from HTML elements does not change.

Look at jQuery for JavaScript

After gaining a basic understanding of JavaScript, the natural progression would be to look at jQuery for JavaScript.

The previous post demonstrated a simple web page that displayed the heading “Hello”, and it would log the same to the console each time a user clicked on the heading.

This next bit of code is rather simple, but it takes a huge leap forward in terms of capability. It introduces the concept of page interactivity. In other words, a page can have dynamics based on how the user interacts.

<head>
++<script src=”http://code.jquery.com/jquery-1.11.3.min.js”></script>
</head>

<body>
++<h1 id =”title” onclick=”$(‘#title’).html(‘Goodbye’);”>
++++Hello
++</h1>
</body>

 

The src attribute inside the <script> tag links the HTML document to the jQuery library. jQuery is a library of built-in JavaScript functions that makes using JavaScript faster and easier. Much like Bootstrap is a CSS library built for CSS3 that does lots of the heavy lifting for page styling, jQuery works in a similar way by making it easier to manipulate pages using JavaScript.

Breaking Down jQuery for JavaScript

In the above example, look at the code after the onclick attribute. It can broken down as follows:

  • The dollar sign $, calls on the jQuery library.
  • The argument ‘#title’, is a CSS selector that indicates selection of an HTML element by its id. In this case, the id is “title”. While elements can be selected by tag or class, id is normally used to select exactly one element.
  • The .html is calling a function to change the text of the element.
  • Finally, the ‘Goodbye’ is what the heading changes to. Click on “Hello”, and it will change to “Goodbye”.

In summary, this post demonstrated a simple interactive web page. This concept can quickly be expanded to create rich, interactive web experiences.

Download the jQuery library for free.

Web Browser Console and JavaScript

The web browser console is very useful for JavaScript. To access the browser console in Chrome, open the menu, click tools, and then developer tools. There should be a tab for console in the top menu bar.

Check the documentation for other browsers on how to access the console in those browsers.

Shown below is some simple HTML code that can be used to interact with the browser console:


<body>
++<h1 id ="title" onclick="console.log('hello');">
++++Hello
++</h1>
</body>

 

The console will log ‘hello’ each time the <h1> element is clicked.

Think of JavaScript as having the ability to work with different ‘objects’. The console is one object. HTML tags can be other objects, and the HTML document itself is an object. Interacting with these various objects represents the vast majority of what web developers do with JavaScript.

In the above example, look at the code "console.log('hello');". The log function is being called on the console. While this code is rather simple, it’s extremely important on a conceptual level. It underscores the relationship of how to call functions on objects. The ‘.’ between ‘console’ and ‘log’ is what links the object to the function. Developers often debug or test JavaScript code by printing to the browser console.

Interactive JavaScript – The Basics

To look at a basic web page, the computer’s browser sends a URL request to a server that hosts the page to be viewed. The server finds the HTML page, and sends it back to the browser, along with CSS styling. This interaction describes web pages up through the mid to late 1990s. However, a modern web page is more interactive. Interactive JavaScript programming is a skill modern web developers must know.

How JavaScript Works with HTML5 and CSS3

A modern web page can interact with the end-user without having to load new pages. It can play a video, show drop down menus, take field input, etc. JavaScript is the language that enables this type of interactivity.

To break it down, HTML provides the structure, CSS provides the styling, and JavaScript enables interactivity. JavaScript is a high functioning language, so it will probably not be as easy to learn as HTML or CSS.

It’s important to note that JavaScript is not the same as Java. These are two completely different programming languages.

Write Your First Interactive JavaScript

<h1 id="title" onclick="alert('hello');">Hello</h1>

the above <h1> tag in HTML contains an onclick event. The onclick event attribute is when the end-user clicks on the <h1> heading. The "alert('hello');" is JavaScript that tells the browser what to do when the onclick event occurs, i.e., when the end-user clicks on the heading. Everything else is HTML, except for this little script.

In the example above, a box will pop up that says "Hello" when a user clicks on the heading. The alert is a function that tells JavaScript what to do. The ('hello') part of the script is referred to as the argument. It tells the function how to do what it has to do.