Application Development Blog Posts
Learn and share on deeper, cross technology development topics such as integration and connectivity, automation, cloud extensibility, developing at scale, and security.
Showing results for 
Search instead for 
Did you mean: 
We're back this week to explore the fundamental elements of web development before we move into more complex topics. This weeks focus is JavaScript. If you haven't checked out my previous blogs for the trifecta of web development, check out my blog posts on HTML and CSS.

JavaScript: a once feared technology is now (and has been for a while) a de-facto choice for development. It allows you to program dynamic behavior on your web page.

JavaScript is at the basis of commonly used frameworks we will explore later. It is the foundation of the MEAN stack - the standard of web development today. MEAN stands for M: MongoDB (backend/database), E: Express (NodeJS module for ease of use on the backend with HTTP), A: Angular (frontend framework for page structuring), and N: NodeJS. We will explore NodeJS in the coming weeks!

But before we cover all the sexy stuff, let's understand the basics of JavaScript and how it interacts with out page. JavaScript (or JS henceforth) allows us to manipulate the DOM (Document Object Model).The DOM is what helps us understand what is on the HTML page (because HTML is a document). It breaks the HTML page into nodes that we can easily understand with other languages like JS.

To show you an example of this, let's add a little button with some JS to our page. Open your index.html file.

Under your profile link, let's define a new button tag.
<button>Load the picture</button>

Maybe add a couple break lines ( <br /> ) - this is the equivalent of hitting the enter key on a word document. This is bad styling habit as an FYI, but for beginner purposes, it will be ok cause we will fix it when we talk about Bootstrap in the coming weeks.

SAVE your changes, and open your index.htm file in the browser.

This will create a new button element on your page.

If you click this button, it will do nothing currently. Let's change that! This is where you get to add a little JS. We can define the "onclick" event attribute. Event attributes allow us to trigger the JavaScript code when the element is interacted with. For example, onclick fires when the button is...wait for it...clicked!

Another key piece to manipulate the DOM is IDs. All tags should have IDs. This makes them accessible via their ID.

Let's define a placeholder image tag ( <img> ) below our button, but make sure to give it an ID!
<img id="myImage">

Now we can access this element by the ID myImage.

In the button, add the onclick attribute to the button opening tag. The onclick value will be a small script that will update the value of the src attribute for the image element. We can access the img tag by referencing it's ID, and then we can set the src value. To assign a value to an attribute in JS, we use a single equals (=). Using more than one equals is an equivalence operator, which we'll get too in a minute.

For now, focus on setting the image field's source attribute to a picture. I used an image online of the JS logo.

So your button should look like this:
<button onclick="document.getElementById('myImage').src=''">Load the picture</button>

SAVE your changes, and open your index.html file in the browser.

You will have a button you can now take action on. Click the button and your image will load next to your button.

We can also move the JS out of the element definition if we want to be able to reuse it.

Create a new script.js file in your directory.

Let's define a new function. This way, multiple elements can access it if need. Functions are used contain a block of code that should be executed when called. When a function is called, only the code inside that function block will be executed.

Define a blank function in your new script.js file.
function onPictureButtonClicked() {

It's a good idea to name your functions so it it is easy to understand what they do.

Now, copy the code from the onclick attribute into your new function.
function onPictureButtonClicked(){

SAVE your changes to your script.js file.

To use this new function in your index.html file, we need to a reference to the file (similar to what we did with our CSS style sheet), and then call the function in the onclick attribute.

To tell the index.html file that it can reference the JS code in the script.js file, let's define a <script> tag in the header.  The src is script.js.
<script src="script.js"></script>

This let's our page know the referenceable JS can be found in this file.

Last update is to the button. In the button definition remove the previous code, and replace it with "onPictureButtonClicked()". This will assign that function to the onclick event.
<button onclick="onPictureButtonClicked()">

SAVE your changes. The behavior of your page will be the same. Test it out before we continue, but there will be no visible difference from the web page.

Now let's say we want to change the action is this image is already loaded?

We can have JS do the work for us, but before we do the JavaScript Code, we need to make a little tweak to your HTML. Remember when I said IDs are important? Well we forgot to include one on our button, so go add one!
<button id="pictureButton" onclick="onPictureButtonClicked()">

We want to make sure the button is always reflecting the action we are taking, so we'll need to update the text when changing the functionality.

SAVE your changes, and go back over the script.js file.

In your onPictureButtonClicked function, we need to make some changes.

First thing, let's save a copy of the value of the src attribute. We will need to reference it a couple times, so it's easier to define it once as a variable, and use the variable whenever we need the value.

We can create a variable by using var and a name. Define this right underneath your function definition (so this is the 1st line of your function).
var imageSrc = document.getElementById('myImage').src;

Now whenever we need the initial state of the image src when the function was called, we can reference imageSrc.

Let's take an action based on the current value of the src. If there is nothing, let's load in an image. If there is an image, let's remove the image.

You see how I just used ifs in that previous paragraph? JS notation is very similar to how we would say it is in English. IF the imageSrc is empty, set a value.
if(imageSrc == '') {
document.getElementById('myImage').src ='';

Here we used a double equals ( == ) to do a comparison. This does a value comparison. Best practices in JS state that you should use a triple equals ( === ) as this compares value and types, so they truly are equivalent. This can be tricky but important with null values as not all nulls are created equal.

OTHERWISE, remove the value.
else {

(note: this is also not a great practice as src is a required field for images for many reasons, including accessibility. This is purely for demonstration purposes.)

I mentioned earlier that buttons should always state their intended action. If our code is removing an image, does "Load Image" make sense? Nope. So we need to fix this.

You can update the button text similarly to how we update the src element for the image, except instead of the src property, you would use the innerHTML. Give it a try!

Need some help?

Your script.js file should look like this:
function onPictureButtonClicked(){
var imageSrc = document.getElementById('myImage').src;

if (imageSrc == '') {
document.getElementById('myImage').src ='';
document.getElementById('pictureButton').innerHTML = "Remove Picture";
} else {
document.getElementById('pictureButton').innerHTML = "Load Picture";

SAVE your changes, and open your index.html file in the browser.

If you click the button, the image will load and the button text will change to Remove Image. If you click the button again, it will remove the picture and change the button text to Load Image. Neat!

This was just a little primer to what you can do with JavaScript! If I was to cover everything, I think I would be doing this for 3+ years 🙂

I encourage you to explore JS a bit more - there's a great course on JavaScript in CodeAcademy if you want to become more of an expert!
Labels in this area