How to Build Javascript Components Without a Frameworks

How to Build Javascript Components Without a Frameworks

In this post, I’ll show you how to build a simple star rating component using nothing but vanilla JavaScript, CSS, and HTML. I’ll be using VS Code and http-server to build and serve a static set of files.

Everyone has their favorite framework, and most developers aren’t shy about sharing those opinions. I guarantee you right now two developers are arguing about their favorite frameworks. Personally, I’ve been using JavaScript frameworks since JQuery was introduced. I’ve written applications for clients using Knockout.js, Angular 1+, React (since before v15), and have made some small learning apps using Stencil and Vue.

One of the great things that all of these frameworks bring to the table is their easy composability. The ability to make components that you can reuse throughout your app helps so much with development time, code reusability, and testability. You don’t have to use a framework to get these benefits. JavaScript has them built-in, you just have to know where to look. Also, learning how to build components in vanilla JavaScript will help you understand how to make those components in your favorite framework.

In this post, I’ll show you how to build a simple star rating component using nothing but vanilla JavaScript, CSS, and HTML. I’ll be using VS Code and http-server to build and serve a static set of files. You’ll need Node.js and npm installed to run http-server.

Define the Desired Behavior for the JavaScript Component

When I build components in any framework (or without one), I like to first figure out all the things I need the component to handle internally. In this case, I’m building a star rating component, so it definitely needs to display stars.

  • The star component will have a default color for all the stars.
  • If the component has a rating value when it renders, it should change the color of all the stars up to and including the star that denotes the rating.
  • When a user hovers over the component every star in the component, up to and including the one they are hovering over, should change colors.
  • If the user clicks on a star, the current rating for the component should be updated to reflect the star rating they clicked on.
  • If they move their mouse away without selecting a rating, the component should set the colors of the stars back to reflect the last selected rating.

With those requirements in mind for your JavaScript component, let’s dig in!

Build the Shell of the JavaScript Component App

Start by creating a folder somewhere you want to serve the application from. When you run http-server in a directory it serves that folder as a web server. Once you have the directory created, open it in VS Code and add a file called index.html. This will be your web application. Inside the index.html. This file will have two star rating HTML elements on it along with some basic style and a script tag. The complete contents:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <style>
    .star-rater .star {
      font-size: 5rem;
      color: gray;
    }
  </style>
  <title>Rater</title>
</head>

<body>
  <h2>Star Rating</h2>
  <div id="rater-1" class="star-rater" data-rating="3" role="rater">
    <span class="star" data-value="1">&#9733;</span>
    <span class="star" data-value="2">&#9733;</span>
    <span class="star" data-value="3">&#9733;</span>
    <span class="star" data-value="4">&#9733;</span>
    <span class="star" data-value="5">&#9733;</span>
  </div>

  <div id="rater-2" class="star-rater" data-rating="2" role="rater">
    <span class="star" data-value="1">&#9733;</span>
    <span class="star" data-value="2">&#9733;</span>
    <span class="star" data-value="3">&#9733;</span>
    <span class="star" data-value="4">&#9733;</span>
    <span class="star" data-value="5">&#9733;</span>
  </div>

  <script type="module" src="js/main.js"></script>
</body>

</html>

You’ll notice I’ve added the role="rater" to each element. That will be the way you tell the main JavaScript file to attach the functionality of your Rater component to this element.

Now create a folder called js to house your vanilla JavaScript component code, and then create two files called rater.js and main.js inside that new folder. That script tag above brings in the main.js file as a module type. For browsers that support module syntax for JavaScript, this will allow you to use the import and export statements introduced in ES2015.

In the rater.js file add the code to export the rater’s functionality:

export function Rater(ratingElement) {
  const stars = ratingElement.querySelectorAll('.star');
}

The first bit of functionality is here as well. The Rater takes in an HTML element and queries it for all of its elements with a class of star and puts them into the stars array.

To finish out the shell, add the code to the main.js file that finds all the HTML elements with a role of rater and pass them to the Rater component.

import { Rater } from './rater.js';

document.addEventListener('DOMContentLoaded', function() {
  const raters = document.querySelectorAll('[role=rater]');
  raters.forEach(rater => {
    new Rater(rater);
  });
});

Now you should be able to fire up the application by serving the folder. From the folder where your index.html file lives in a console run:

http-server .

It will tell you it’s running on http://localhost:8080, and you will see the two rating components with gray stars, but they don’t do anything yet.

Build the Functionality of the JavaScript Component

Start with add the ability to highlight based on a rating number. In the rater.js file, add a function to highlight each star up to and including a certain rating:

const highlightRating = (rating) => {
  stars.forEach(star => {
    star.style.color =
      rating >= star.getAttribute('data-value') ? 'yellow' : 'gray';
  });
}

Now you’ll want to set the initial highlighting for the component when it renders. Each rater HTML element has a data-value attribute. That will be used to hold the current rating for the component. Since you’ll use this when the component loads and after the user moves their mouse away from the component, call the function resetRating(). Add the following function right above the highlightRating() function:

const resetRating = ev => {
  const currentRating = ratingElement.getAttribute('data-rating');
  highlightRating(currentRating);
};

Then below the highlightRating() function call it so that you can set the highlighting for the initial load.

resetRating();

Now when you reload your browser you should see each rater highlighted to its appropriate default rating. In this case, three and two.

The next step is to handle the hovering action so that the rating component highlights as the user hovers over it. You’ll first need to wire up an even to each star. Since you already have all the stars in the component in an array, just loop over them and hang the event listener on them. Add the following code to the bottom of the component function:

stars.forEach(star => {
  star.addEventListener('mouseover', ratingHover);
});

Now, you need the event handler for the listener. This even will just get the star the user’s mouse is hovering on and call the highlightRating() function. Right above the resetRating() function add:

const ratingHover = ev => {
  const currentHover = ev.currentTarget.getAttribute('data-value');
  highlightRating(currentHover);
};

You’ll also want the component to reset back to the last selected rating (in this case the default rating) when the user moves their mouse away from the rating component. Add the following line of code to the bottom of the component function:

ratingElement.addEventListener('mouseout', resetRating);

Now if you refresh your page you should see the hovering happening and when you move the mouse away, it should reset the highlighting.

Now there is only one thing left to do, and that is wire up a click event to the stars and update the data-rating for the component when a user clicks on a star.

To wire up the click event, update the stars.forEach() line so that it looks like:

stars.forEach(star => {
  star.addEventListener('click', setRating);
  star.addEventListener('mouseover', ratingHover);
});

Now that you have a listener for the click and the hover, add the setRating() event handler to set the rating when a user clicks on a star below the first line of the component function:

const setRating = ev => {
  ratingElement.setAttribute(
    'data-rating',
    ev.currentTarget.getAttribute('data-value')
  );
};

Now, when you refresh your browser, you should be able to hover over the rating component and see the highlighting happening. Then, when you click on a star, it should update the data-rating value of the rating component element. You can view this in the developer tools of your browser.

Take the JavaScript Component to the Next Level

I’ve kept this component simple to illustrate just how to make the component and make it reusable by the import statement. Now that you know how to build and use a component in vanilla JavaScript, you could make this component do so much more!

You could have the component “draw” the stars and set a max-stars attribute on the element to tell the component how many stars to draw. You could use something like Font Awesome to display other things besides stars. You could even make the Rater component call another component that sends the rating that the user selects back to an API to be saved to a database. But the skeleton is there.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Programming a Javascript Simon Game Tutorial

Programming a Javascript Simon Game Tutorial

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

For those who don't know, I'm a full stack web developer who has been in the industry for over 5 years now. There is a lot of things I have learned along the way and I'd like to share that knowledge with anyone wanting to learn!

like this video if you found it useful and would like to see more videos of the same content.

subscribe to my channel if you are trying to improve your abilities as a web developer, software engineer, or even if you are just learning to code.

Don't forget to turn on those bell notifications!

Understanding Memoization And Dynamic Programming in Javascript

Understanding Memoization And Dynamic Programming in Javascript

In this Javascript tutorial I will explain what memoization is, how to use it, when you should use memoization, how to use memoization, what dynamic programming is, how to use memoization in dynamic programming. Memoization is a big complicated word that you may have never even heard before, but you may be surprised to know that you are most likely already using memoization without even realizing it.

Memoization is a big complicated word that you may have never even heard before, but you may be surprised to know that you are most likely already using memoization without even realizing it. Memoization is just the act of caching values so that they can be calculated quicker in the future. Memoization is really useful in all parts of programming, but where it is most useful is in dynamic programming. In this video I will explain what memoization is, how to use it, and why it is so useful especially in dynamic programming.

🧠 Concepts Covered:

  • What memoization is
  • When you should use memoization
  • How to use memoization
  • What dynamic programming is
  • How to use memoization in dynamic programming

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

JavaScript is the programming language of HTML and the Web. JavaScript is easy to learn. This tutorial will teach you JavaScript from basic to advanced. JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Watch this JavaScript tutorial for beginners to learn JavaScript programming from scratch. 👍

⭐️Course Contents⭐️

01 | Introduction

Get an introduction from Bob, as he kicks off the course, sets expectations, and gives you a little guidance for the road ahead.

02 | Setting Up the Development Environment

See how to install Node and Visual Studio Code, and learn why you need each. Watch as Bob writes a first tiny line of code to make sure that the installation is ready.

03 | Basic JavaScript Syntax

Hear about the basics of the JavaScript syntax, including how JavaScript is executed, how to create a properly formed statement, and more.

04 | Variables

Learn what variables are and how to declare, initialize, set, and get values from them.

05 | Data Types

JavaScript works with data types differently than other programming languages do. Learn from Bob as he explains some of the most basic data types and how to determine the type held by a variable.

06 | Type Coercion and Conversion

Sometimes you need to explicitly convert the data type of a value into a different data type. Sometimes JavaScript will do this automatically for you. Bob explains how and why this happens.

07 | Expressions and Operators

Learn how to spot a well-formed expression and how to compose expressions through the combination of operators and operands.

08 | Arrays

Watch as Bob demonstrates how to use arrays, how to add/remove elements of an array, how to access elements of an array using the index, how to get the number of elements in an array, and more.

09 | Function Declaration

Get an introduction to functions, as Bob shows you one way to define a function, how to call the function, how to pass parameters into a function, how to return values from a function, and more.

10 | Function Expressions

Sometimes a function declaration is more than you need. Get details in this lesson, as Bob demonstrates how to use a function expression and how to create an immediately invoked function expression.

11 | Decision Statements

Learn how to add logic to your applications by testing conditions using if / else statements, switch / case statements, and the ternary operator.

12 | Iteration Statements

Watch as Bob introduces the For and While statements, which enable you to loop through lists of values and perform operations on them.

13 | Basics of Scope

Hear an explanation of the notion of the lifetime of variables and their reach into other code blocks, in this discussion of scope.

14 | Returning Functions from Functions

As a building block toward a more sophisticated approach to building JavaScript applications, see how you can return functions from functions.

15 | Object Literals

Objects contain properties and functions that describe attributes of the object and its behavior, respectively. Watch as Bob demonstrates how to create object literals.

16 | Module Pattern and Revealing Module Pattern

Learn how to introduce variables and functions without leaving an unnecessarily large footprint on the global scope.

17 | Closures

Closures allow developers to bind functions to their execution context, including variables, so you can build specialized versions of functions. Learn how closures work and how to create them.

18 | this Keyword

Get the details on the "this" keyword, which causes a lot of confusion for JavaScript developers. Listen as Bob explains what this mysterious object is and how to bend it to your will.

19 | Destructuring

See how to use destructuring, a new feature in JavaScript that allows you to unpack array elements or object properties in a concise syntax.

20 | String Template Literals

Learn about the new string template literal syntax to enable string interpolation, multi-line string formatting, and more.

21 | Regular Expressions

Working with string data, Bob explains how use regular expressions to determine such things as whether a string matches a specific pattern or whether an instance of the pattern exists in a string.

22 | Built-In Natives

Join Bob as he examines native, built-in JavaScript functions that return objects that box the primitive types in order to provide additional helper methods on your values.

23 | Constructor Function Calls with the new Keyword

Learn how constructor functions work, see how to make key distinctions in what they are, and find out why they’re helpful.

24 | Objects and the Prototype Chain

Moving past the absolute beginner matter, listen in as Bob explains how objects work in JavaScript and how you can create an object that is linked to another object.

25 | JavaScript Classes

Bob demonstrates how “syntactic sugar” works on top of the existing functions and prototype chaining to help JavaScript resemble more traditional object-oriented programming languages.

26 | Arrow Functions

The latest version of JavaScript added arrow functions, a shorthand syntax for creating functions. Watch as Bob demonstrates how to create them and shows where they’re useful.

27 | Truthy and Falsy Values

Listen is as Bob circles back to topics that are important (but didn’t easily fit into earlier topics) and looks at the odd way in which JavaScript evaluates certain expressions as truthy and falsy.

28 | null Type

Similar to the undefined primitive type, the null type represents a variable that has no reference to an object when one was expected. Hear an explanation of how and why we should think about nulls.

29 | Date Objects

No discussion of JavaScript would be complete without understanding the Date built-in native function which provides properties and methods for working with dates and times.

30 | String Methods

The built-in native String function provides several very useful methods for manipulating and evaluating strings. Watch Bob demonstrate how to use a few of the most useful ones.

31 | Array Methods

We’ve worked with arrays throughout this course. Now Bob takes a few minutes to show you some of the most useful methods provided by the Array built-in native function.

32 | Error Handling with Try Catch

See how to wrap a try/catch/finally statement around potentially problematic code to anticipate everything that could go wrong with it, and learn other error-handling tips.

33 | Understanding the Document Object Model

Watch Bob examine the web browser environment and how it creates an object graph of nodes that represent elements, their attributes, and text, plus how to properly attach your code to an HTML page.

34 | Working with DOM Nodes

Continuing from the previous video, Bob demonstrates a slightly more compelling example that helps us understand how to manipulate, create, and delete element nodes and attribute nodes.

35 | Course Conclusion

In this final video, Bob briefly adds some closing comments and well wishes. You can also optionally complete a survey to provide insight into how Microsoft can improve this course.

Thanks for watching

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter