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

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.