Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Big Bang of Web Development: Get Moving With JavaScript

DZone's Guide to

The Big Bang of Web Development: Get Moving With JavaScript

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.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

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 (Node.js module for ease of use on the backend with HTTP), A: Angular (front-end framework for page structuring), and N: Node.js. We will explore Node.js in the coming weeks!

But before we cover all the sexy stuff, let's understand the basics of JavaScript and how it interacts with the 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. 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 its 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 to in a minute.

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

document.getElementById('myImage').src='https://www.javatpoint.com/images/javascript/javascript_logo.png'

So your button should look like this:

<button onclick="document.getElementById('myImage').src='https://www.javatpoint.com/images/javascript/javascript_logo.png'">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 needed. Functions are used to 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 is easy to understand what they do.

Now, copy the code from the onclick attribute into your new function.

function onPictureButtonClicked(){
document.getElementById('myImage').src='https://www.javatpoint.com/images/javascript/javascript_logo.png';
}

SAVE your changes to your script.js file.

To use this new function in your index.html file, we need to add 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 lets our page know the referenceable JS can be found in this file.

Lastly, update the button. In the button definition, remove the previous code and replace it with onPictureButtonClicked(). This will assign that function to the onclick event.

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 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 our HTML. Remember when I said IDs are important? Well, we forgot to include one on our button, so let's 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 fist line of your function).

var imageSrc = document.getElementById('myImage').src;

Now whenever we need the initial state of the image src when the function is 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 vocalize and if, then statement English. If the imageSrc is empty, then set a value.

if(imageSrc == '') {
    document.getElementById('myImage').src ='https://www.javatpoint.com/images/javascript/javascript_logo.png';
}

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 {
    document.getElementById('myImage').removeAttribute('src');
}

(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 similar to how we updated the src element for the image, except instead of the src property, you would use 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 ='https://www.javatpoint.com/images/javascript/javascript_logo.png';
    document.getElementById('pictureButton').innerHTML = "Remove Picture";
  } else {
    document.getElementById('myImage').removeAttribute('src');
    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 on CodeAcademy if you want to become more of an expert!

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,javascript ,mean stack ,front-end development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}