Web Development for Embedded Engineers: Javascript (JS)

JavaScript inscription against laptop and code background. Learn JavaScript programming language, computer courses, training.

In a previous article, we talked about web development basics, especially HTML and CSS. These technologies are responsible for creating the layout and styles of a website. This is enough to give us a static site, which nowadays is not enough. To add that missing dynamic functionality, we need to provide JavaScript.

Perfect Timing. Try Our ARM® Embedded Dev Kit Today.

Netburner ARM Cortex M7 embedded Development Kit for IoT product development and industrial automation.

Or, learn more about NetBurner IoT.

In this article, we’ll describe some basic concepts needed to get started with JavaScript. We’ll also show how to implement it in our embedded systems projects, as well as provide some links that may be useful.

Introduction

Continuing with the construction example from the previous article, we already have a building with the structure (HTML) and all the decorative details (CSS). In theory, it’s already a livable house. However, we can still add things internally, such as a stove, a refrigerator, LED lights, etc., that make the house more functional as a living space. 

This is where JavaScript (JS) comes in, and it’s personally my favorite part of web development.

JavaScript is a lightweight, multi-platform, object-oriented programming language and is very simple to learn. It’s currently one of the most widely used technologies in web development for both Front-End and Back-End (servers, databases, etc.).

The most robust frameworks for developing web systems use JavaScript (Angular, Vue, React). It’s a technology that is constantly changing. I recommend looking at this website, State of JS 2020, to get a better understanding of the current JavaScript landscape. It’s updated every year with the language’s new features, the popularity of frameworks, new libraries, etc.

In the rest of this article, we’ll show some code snippets that can serve as a handbook when developing with JS.

Add JavaScript code to HTML code.

There are two ways to add JS code to your website:

  1. Directly into the HTML file: This is done using the <script> </script> tag where everything inside is the JS code. It’s usually placed between the <head> or <body> tags.
Where to add javascript code
Figure 1: Places to put JS code.
  1. Externally in a .js file: The method is to use an external file for the JS code. The file must have the extension “.js.” We must add the src attribute to the <script></script> tag, and the file can be hosted in your local directory or on a cloud server.
Types of script src
Figure 2: Types of src in script tag

You can find more information about when to use each option here.

DOM Handling.

One of the most important concepts of web development is understanding how to handle the Document Object Model (DOM). It’s the representation of the website’s structure in an object that can modify page elements and styles using JS code. 

The DOM organizes HTML elements in a hierarchical (or also called tree) system. Each level of the hierarchy can have parent and child elements. Figure 3 shows an example of the DOM representation.

Figure 3: Example of DOM

The DOM isn’t part of JavaScript libraries or functions. Instead, it’s intrinsic to each web browser (e.g., Chrome, Firefox, Safari, etc.), implemented with something called WEB APIs. These are libraries (also coded in JS) that can interact within our code. Although there is a standard for libraries written for the DOM, sometimes web browser developers implement some extra functions. That’s why web pages sometimes look better in some browsers than others.

More information about the DOM is here.

Get DOM elements

There are several ways to access DOM elements from JS:

  • Get element by ID: This returns the element with the provided ID, or null if it doesn’t exist.
				
					const element = document.getElementById('');
				
			
  • Get elements by Class: This returns an array of type HTMLCollection, where all of the included elements have the selected class. The array elements are fetched according to their order of appearance in the DOM.
				
					const elements = document.getElementsByClassName('');
				
			
  • Get elements by tag: This returns an array of type HTMLCollection, where all the included elements are of the specified tag.
				
					const elements = document.getElementsByTagName('');
				
			
  • Get elements by query: This function gets the elements according to the specified query. An element can be retrieved by ID using the ‘#’ symbol (e.g., querySelector(‘#header’)), by class using the ‘.’ symbol (e.g. querySelector(‘.btn’)), or by tag name (e.g. querySelector(‘h4’)). It can even obtain an element by pseudo class(e.g. querySelector(‘li:last-child’)), which is one of its most important functionalities.
				
					const element = document. querySelector('');
				
			

If there is more than one element, it will return the first one it finds. If you want to get all of the elements, the following method is what you need:

				
					const elements = document. querySelectorAll('');
				
			

With this function, you obtain an array of type NodeList elements that match the given query.

This article explains the difference between NodeList and HTMLCollection. 

Choosing which way to get the HTML elements is more a matter of taste (and specific circumstances) since all browsers support the five approaches. I prefer to use querySelector() because it’s more versatile and simplifies the code. Still, there are occasions where it’s required to use another method to get the HTMLCollection array.

 

Modify DOM elements content.

Once we have obtained the elements, we can modify their content, depending on their characteristics. The most common elements are text type or input type.

To modify the inner content of text-type elements, we use the textContent method. For changing the input value of input-type elements, we use the value method. In figure 4, you can see an example of how to change text and input values.

Example of how to change input content
Figure 4: Process to change text and value of DOM elements.

Create DOM elements.

We can create HTML elements directly from our code with JavaScript, creating dynamic content on the web page. There are two methods for building elements.

  • Create from scratch: In figure 5, you can see a small diagram of the basic steps used to create an element from scratch and an example of how to do it in code.
Process to create a DOM element from scratch
Figure 5: Process to create a DOM element from scratch
				
					/* Create html element */
const newElement = document.createElement('p');
/* Add styles, classes, content, etc. */
newElement.style.color = '#f2f2f2';
newElement.textContent = 'This is a dynamic element';
/* Get node to add element */
const body = document.querySelector('body');
/* Append or prepend to a Node */
body.prepend(newElement);

				
			
  • Automatic creation: This is a reduced form and is my personal favorite. Figure 6 shows the necessary steps to do it, and a snippet code below:
Process for automatically creating a DOM element
Figure 6: Process for automatically creating a DOM element
				
					/* Create template string */
const html = `<p style="color: #f2f2f2">This is a dynamic element </p>`;
/* Get node to add element */
const body = document.querySelector('body');
/* Insert Adjacent HTML */
body.insertAdjacentHTML('afterend', html);

				
			

In the following link, you can find more information about the first parameter of the insertAdjacentHTML() method.

Change styles.

The ability to modify styles of an element dynamically from JavaScript is one of its most used functionalities, especially when we use JS-free CSS frameworks. We have two ways to perform this task:

  • Edit inline styles: This modifies the style of the element directly. The syntax for getting or modifying an inline style is as follows:

<DOM object>.style.’<CSS rule (camelCase)>’

Example:

				
					/** Getting the style  */
const style = document.querySelector('p').style.backgroundColor;
/** Changing the style */
document.querySelector('p').style.backgroundColor = '#B91C1C';

				
			
  • Edit classes: This is the most common way to change styles and is also considered a best practice. To handle classes, the “classList” property is used, which contains the following methods:

Deletes one or more classes from an element.

				
					remove(&ldquo;class1&rdquo;[,&rdquo;class2&rdquo;[,...&rdquo;classN&rdquo;]])
				
			

Adds one or more classes to an element.

				
					add(&ldquo;class1&rdquo;[,&rdquo;class2&rdquo;[,...&rdquo;classN&rdquo;]])
				
			

If the class exists, it removes it; otherwise, it adds it.

				
					toggle(&ldquo;class1&rdquo;)
				
			

Replaces one class with another

				
					replace(&ldquo;oldClass&rdquo;, &ldquo;newClass&rdquo;)
				
			

Returns a boolean value for the existence of a class in an element.

				
					contains(&ldquo;class&rdquo;)
				
			

One example of how to use this is as follows:

				
					/* Create an element */
const myElem = document.createElement('div');
/* Add class "MyClass" */
myElem.classList.add("MyClass");

				
			

Event Handling.

JavaScript has a compelling feature, the ability to execute code asynchronously with externally triggered events, such as clicks, hover, scroll, keypresses, etc. Events make JS the perfect complement to HTML and CSS since it allows the user to interact with the system.

In the old days we used what is known as inline events, also called “onEvent”. Nowadays, that is considered bad practice. The current way to handle events is using the addEventListener method, which is available for any DOM element. An example of how to assign an event to an element is as follows:

				
					/* Add click event listener */
document.querySelector('p').addEventListener('click', () =&gt; {
  console.log('You clicked');
});

				
			

Event handling is a complex topic because there are a lot of events to use and considerations for each one. To start with, we recommend the following documentation, which explains an introduction to events.

HTTP Request Using Fetch

One of the most common tasks in JavaScript is to request information from external sources using the HTTP protocol (more details in our article An Introduction to the HTTP Protocol).

In the old days, we used to play with the XMLHttpRequest object to get data asynchronously with HTTP. Now, it’s considered good practice to use the native JS library called Fetch. It does the same job, but the big difference is that Fetch works with Promises, making it easier to handle the responses.

To understand a little more about the difference between Fetch and XMLHttpRequest, I recommend reading the following guide.

To learn how to use Fetch, you can use the following link as a guide.

If you’re confused by the term Promises, I recommend that you first look at the asynchronous functionality of JS and then check out this link that explains how promises work.

Embedded web pages using NetBurner

At NetBurner, we know how complicated it can be to create embedded systems with web pages. For example, in a Raspberry Pi, you would have to install and configure a web server like NGNIX and then, with some line commands, put your web page files in the public folder, etc. If we talk about doing the same thing for a traditional microcontroller … that’s a much longer process. That’s why our systems already come with everything you need to serve your embedded pages in four easy steps.

  1. Create a project for your development system. It can be using our NBEclipse tools or from terminal commands. See our online documentation for more information.

2. In the HTML folder of the project, place your web page files.

3. Compile your project, and load it onto your device.

4. Open a web browser (e.g., Chrome, Firefox, Safari, etc.) on a device that is on the same network as your NetBurner module and enter its IP address.

We have a wide variety of examples, which you can find in the path:

\nburn\examples\Web

In this article, you’ll find information on how to generate dynamic content on your site.

Also, if your website is quite robust, you can host the files on external memory (MMC/SD). Examples of how to do this are at the following path in your NNDK toolset:

\nburn\examples\EFFS\Fat\Http

Next Steps

Now that you know some essential web development concepts, studying and practicing with real examples is next. SPOILER ALERT!!, it’s going to be a challenging road because there are many new tools to learn, but with patience, persistence, and perseverance, you can do it.

My recommendation: take courses. You can find many courses that take you from zero to expert with real projects on the internet. As a first resource, you can use YouTube tutorials; the advantage is that these are free, the disadvantage is that these may not be well organized, and when you finish it, you may have doubts about where to continue. Many other websites offer courses on web development and provide a more structured approach to learning the material.

Wrapping Up

Hopefully, this article will be valuable for those of you who are just starting to get into web development. This article aims to be a handbook of some of the most useful pieces of JavaScript’s functionality to get you started and point you in the direction of some additional resources that can help you go much deeper.

We’d love to read your comments, so don’t be shy; the section below is yours.  If you have any questions, require more information, or have a topic you would like to see in future articles, feel free to email us directly at sales@netburner.com.

Share this post

Subscribe to our Newsletter

Get monthly updates from our Learn Blog with the latest in IoT and Embedded technology news, trends, tutorial and best practices. Or just opt in for product change notifications.

Leave a Reply
Click to access the login or register cheese