Events

Introduction

Now that we have a handle on manipulating the DOM with JavaScript, the next step is learning how to make that happen dynamically, or on demand! Events are how you make that magic happen on your pages. Events are actions that occur on your webpage such as mouse-clicks or keypresses, and using JavaScript we can make our webpage listen and react to these events.

There are three primary ways to go about this: you can attach functions attributes directly on your HTML elements, you can set the "on_event_" property on the DOM object in your JavaScript, or you can attach event listeners to the nodes in your JavaScript. Event listeners are definitely the preferred method, but you will regularly see the others in use, so we’re going to cover all three.

Learning Objectives

  • How do "events" and "listeners" work? What are three ways to use events in your code?
  • How does "bubbling" work?

We’re going to create 3 buttons that all alert "BUTTON" when clicked. Try them all out using your own HTML file, or using something like CodePen.

Method 1 (Not recommended)

<button onclick="alert('Hello World')">Click Me</button>

This solution is less than ideal because we’re cluttering our HTML with JavaScript. Also, we can only have 1 "onclick" event per element.

Method 2 (Not recommended)

<!-- the html file -->
<button id="btn">Click Me</button>
// the JavaScript file
const btn = document.querySelector('#btn');
btn.onclick = () => alert("Hello World");

(need to review arrow functions? Arrow Functions Basics)

This is a little better. We’ve moved the JS out of the HTML and into a JS file, but we still have the problem that a DOM element can only have 1 "onclick" property.

Method 3 (Recommended)

<!-- the html file -->
<button id="btn">Click Me Too</button>
// the JavaScript file
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
  alert("Hello World");
});

Now, we maintain separation of concerns, and we also allow multiple event listeners if the need arises. Method 3 is much more flexible and powerful, though it is a bit more complex to set up.

Note that all 3 of these methods can be used with named functions like so:

<!-- the html file -->
<!-- METHOD 1 -->
<button onclick="alertFunction()">CLICK ME BABY</button>
function alertFunction() {
  alert("YAY! YOU DID IT!");
}

// METHOD 2
btn.onclick = alertFunction;

// METHOD 3
btn.addEventListener('click', alertFunction);

Using named functions can clean up your code considerably, and is a really good idea if the function is something that you are going to want to do in multiple places.

With all three methods we can access more information about the event by passing a parameter to the function that we are calling. Try this out on your own machine:

btn.addEventListener('click', function (e) {
  console.log(e);
});

Note that function (e) is a callback from addEventListener. Further explanation of callbacks can be found HERE.

The e in that function is an object that references the event itself. Within that object you have access to many useful properties and functions such as which mouse button or key was pressed, or information about the event’s target – the DOM node that was clicked.

Try this:

btn.addEventListener('click', function (e) {
  console.log(e.target);
});

and now this:

btn.addEventListener('click', function (e) {
  e.target.style.background = 'blue';
});

pretty cool eh?

Attaching listeners to groups of nodes

This might seem like a lot of code if you’re attaching lots of similar event listeners to many elements. There’s a few ways to go about doing that more efficiently. We learned above that we can get a nodelist of all of the items matching a specific selector with querySelectorAll('selector'). In order to add a listener to each of them we simply need to iterate through the whole list like so:

<div id="container">
    <button id="1">Click Me</button>
    <button id="2">Click Me</button>
    <button id="3">Click Me</button>
</div>
// buttons is a node list. It looks and acts much like an array.
const buttons = document.querySelectorAll('button');

// we use the .forEach method to iterate through each button
buttons.forEach((button) => {

  // and for each one we add a 'click' listener
  button.addEventListener('click', () => {
    alert(button.id);
  });
});

This is just the tip of the iceberg when it comes to DOM manipulation and event handling, but it’s enough to get you started with some exercises. In our examples so far we have been using the ‘click’ event exclusively, but there are many more available to you.

Some useful events include:

  • click
  • dblclick
  • keypress
  • keydown
  • keyup

You can find a more complete list with explanations of each event on this page.

Avoiding Confusion

As you’ve seen, you can define an event handler in 3 different ways.

  1. Using the addEventListener method (Recommended)
document.querySelector(".box").addEventListener( "click", function( event ){ ... });
document.querySelector("form").addEventListener( "submit", function( event ){ ... });
document.body.addEventListener( "keyup", function( event ){ ... });
  1. Using the on<EVENTNAME> property syntax (Not recommended)
document.querySelector(".box").onclick = function( event ){ ... };
document.querySelector("form").onsubmit = function( event ){ ... };
document.body.addEventListener.onkeyup = function( event ){ ... };
  1. Using an attribute with the on<EVENTNAME> directly in an HTML element (Not recommended):
<div class="box" onclick="clickHandler()">Click me</div>
<form onsubmit="submit()">
    <!-- CONTENT -->
</form>
<body onkeyup="handleKey()">

Events in the first syntax are used like this (nouns): ‘click’, ‘submit’, ‘change’, ‘scroll’, etc.

While using the 2nd syntax, are prefixed with the ‘on’ keyword: ‘onclick’, ‘onsubmit’, ‘onchange’, ‘onscroll’, etc.

The second syntax corresponds to element properties and should not be confused with the event names used in the first case.

Additional Resources

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack? Search for: Kostas Minaidis (kostasx)

Feedback

  • Is there anything we can help with up to this point? Do you have something to suggest about this chapter? Let us know in the comments below.

UPDATED: 23.02.2021

Introduction to Vue.JS

Getting Started with Vue.js in 2020

Resources

  • You can watch this documentary and learn about the story behind Vue.JS.
    • Note: this is not a technical tutorial, it’s about the people behind the framework and its evolution.

Duration: 35 minutes

Introduction to React

Introduction

Welcome to the React.JS course. Before diving into the technical nitty-gritty of React, let’s talk a little bit about the history of this popular JavaScript library.

In 2013, React.JS was introduced by Facebook, as a JavaScript library for creating and managing complex user interfaces. It does this by breaking up the interface into independent, composable and reusable chunks of code called Components, which have their own private memory (called the State). Components can be rendered inside the Browser, in the server or through a mobile app (when using React Native) depending on the choice and requirements of the application.

On top of that, React uses a Declarative programming style and abstracts all of the DOM manipulation methods away from us. Creating DOM elements, adding Event Listeners and updating the DOM accordingly can be done in a simpler and much easier fashion in contrast to the standard JavaScript DOM API.

Watch the selected part (up to 04:45) of this next video by Mosh Hamedani in which he talks about the history of React and the concepts of Components and the VirtualDOM.

React, Components and the VirtualDOM in a nutshell by Mosh Hamedani


How does React manage all this complexity and abstracts away the DOM API?

When working with HTML, each element or section of the interface is composed of multiple nested HTML elements. For example, let’s say we want to have a Subscription section:

<section class="subscribe">
    <h2>Subscribe to our Newsletter</h2>
    <hr>
    <p class="suscribe--info">Get whenever the latest release of our newsletter directly to your mailbox</p>
    <button class="subscribe--action">Subscribe</button>
</section>

Whenever we want to re-use this element in different pages or parts of a page, we need to copy and paste whole chunks of code, bloating our HTML code. Worse than that, whenever we want to update this element in some way we need to search through our codebase, find the recurring element and update it in multiple places, a process that is tedious, and most of all, highly error-prone. Is this breaking the D.R.Y. (Don’t Repeat Yourself) principle? Absolutely!

Facing the problems mentioned above, Facebook engineers came up with the brilliant idea of transforming these recurring chunks of code that belong to a single User Interface (UI), into custom HTML Tags called Components. Instead of repeating the same code again and again, it is being abstracted away and placed in a separate file, and a single custom Tag name is used instead, whenever we want the code to appear on our HTML pages.

For example, the previous code can now be placed in a separated file named Subscribe.js (React uses JavaScript to create Components) and a single custom Tag named Subscribe or Subscription can be used in its place, in any page and in any parts of our page. All relevant, element-specific code, including HTML, CSS, media assets and JavaScript, will be placed in a single separate file. Ingenious!

    <h1>Our Application</h1>

    <Subscribe></Subscribe>

    <main>Some content that spans lots of lines goes here...</main> 

    <Subscribe></Subscribe>

React takes a rather radical approach and introduces a new language which unifies HTML, CSS and JavaScript: JSX, short for JavaScriptXML. React developers can write their code in JSX and a special compiler called Babel.JS will transform their code back into HTML, CSS and JavaScript which the browsers can parse and display. A more conservative approach would be to use React with plain old JavaScript, but a lot of the benefits that come along with this powerful new language will be lost.

The reactive part of React comes into play when we bind (connect/sync) specific data to our interface. Whenever this data gets updated, the accompanying DOM elements get automatically updated.

Study: An Overview and Walkthrough

Complete the React Tutorial: An Overview and Walkthrough by Tania Rascia.

Study: Learn React on Scrimba

Complete the Learn React for free series of interactive screencasts at Scrimba.com. To complete the course you must spend around 6 to 7 hours watching the screencasts and and about three times this time to practice and write the code yourself and test it on your local enviroment.

Study: React Guide

Hungry for more React? Dive into the step-by-step official guide. This course will help you crystalize the fundamental concepts of React and write some more code. Remember: 20% theory, 80% code.

Resources

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack? Search for: Kostas Minaidis (kostasx)

UPDATED: 29.12.2020

Feedback

  • Is there anything we can help with up to this point? Do you have something to suggest about this chapter? Let us know in the comments below.

Git Basics – Part I

Reading Time

Until you understand the concepts upon which Git is built, you’ll feel like a stranger in a foreign land., Tom Preston-Werner, author of The Git Parable

"The following parable will take you on a journey through the creation of a Git-like system from the ground up. Understanding the concepts presented here will be the most valuable thing you can do to prepare yourself to harness the full power of Git.

The concepts themselves are quite simple, but allow for an amazing wealth of functionality to spring into existence. Read this parable all the way through and you should have very little trouble mastering the various Git commands and wielding the awesome power that Git makes available to you."

Download and read the The Git Parable

Reading time: 30 to 60 minutes.

Study & Practice Time

Take a 5 to 10 minute break before diving into the next video, as you will not only be learning about the basics of Git and version control, but you will also be practicing these concepts on your own Git repository.

Although the video duration is close to 15 minutes, this session will probably take more than 1 hour (or even more), since you will be practicing along with Colt Steele.

We suggest that you run the commands through the intergrated terminal of VSCode. (Tip: Press Ctrl+J to open/close the terminal while in VSCode)

Duration: 16 minutes

Learn Git in 15 Minutes

Additional Resources

This section contains helpful links to other content. It isn’t required, but you should consider it supplemental if you need to dive deeper into Git and Version Control.

Knowledge Check

This section contains questions for you to check your understanding of this lesson. If you’re having trouble answering the questions below on your own, clicking the small arrow to the left of the question will reveal the answers.

What kind of program is Git?
    • Git is a version control program.
What are the differences between Git and a text editor in terms of what they save and their record keeping?
    • A text editor can only make and save changes to a file.
    • Git tracks changes to the files and their contents over time.
Does Git work at a local or remote level?
    • Git works on a local level. Any changes you make are saved locally with Git.
Does GitHub work at a local or remote level?
    • GitHub works on a remote level. You must push your local changes (using Git) to Github.
Why is Git useful for an individual developer?
    • Git is useful for creating snapshots of your work. If you realize halfway through that you’ve messed up, it’s much easier to reset.
Why are Git and GitHub useful for a team of developers?
    • Git and GitHub are useful for teams because they can merge code together. A developer can work on one part of the code while a second developer works on another part. They can then use Git and GitHub to easily combine their changes.
LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack? Search for: Kostas Minaidis (kostasx)

UPDATED: 25.10.2020

Visual Studio Code

Getting to know the most popular Code Editor

Before diving into the world of Web development, it’s always an important step to get to know our tools.

Since, Visual Studio Code is the editor of choice for this course, take some time to familiarize yourself with the software that will help you build software.

Watch the following video, but try pausing once in a while and test the features described in the video in your version of VSCode.

Duration: Approx. 60~90 minutes

Live Server Extension Set Up

At this point you should be familiar with VSCode, be able to install and uninstall Extensions, configure various aspects and features of the application and work with code files. Also, you should have the Live Server extension installed on VSCode.

Take a look at the next video, in order to understand how you can work with the Live Server extension as we are going to use this setup a lot in the following lessons.

Duration: 2 minutes


Tip: If you are looking for a quick and easy way to position your application windows next to each other, for example having VSCode taking up the left 50% of your screen and the Browser taking up the other right half 50%, you can use some of the shortcuts presented in the videos below (Windows 10).

Launching from the command line (Mac)

Read the following guide on how to setup launching VSCode from the command line on a Mac.

Additional Resources

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack? Search for: Kostas Minaidis (kostasx)

UPDATED: 22.01.2021

CONTRIBUTORS:

Set up all the necessary Services & Accounts

Here is a list of online services and platforms on which you must have an account on.

Please proceed to the checklist and register for a new account on each service. After completing the steps, make sure to send the account names and URLs (e.g. profile) to your instructor.

IMPORTANT: Make sure to use a descriptive, readable username or account name, as this will be your professional profile. For example, avoid usernames such as @mard4354 and prefer/choose ones such as @mary_douglas.


Gmail

By creating a Gmail account you are going to be able to use a multitude of web services provided by Google, such as YouTube, Google Maps, Google Docs, etc.

You will also be using this Gmail account to authenticate yourself with other third-party services, bypassing the time-consuming registration process.

GitHub

A service providing version control for our code. This is a must!

Also, GitHub allows you to register or sign-up with one-click in various services.

Make sure to take good care of your GitHub profile as it will be one of the first stops where employers, recruiters and companies will evaluate your online presence and experience.

Example of a bad GitHub profile page:

Bad GitHub profile page

Example of an awesome GitHub profile page:

cassidoo GitHub profile page

Try to avoid selecting usernames that look akward and unprofessional, e.g. kx345, funny_joe, etc. You probably want to pick a username according to your real name: david_malan, john_resig, etc.

StackOverflow

Join one of the largest communities on the Internet, ask questions, seek for help and contribute.

(You can register with your GitHub account here –recommended)

LinkedIn

We need an account to look professional and also access their learning resources.

Netlify

One of the best hosting platforms out there.

(You can register with your GitHub account here –recommended)

Frontend Mentor

Improve your front-end coding skills by building real projects

(You can register with your GitHub account here)

Codepen.io

An online coding environment. You can easily create a new Code Pen, write some HTML, CSS and JavaScript, and share the code with the rest of the world through a single URL.

Codesandbox.io

An online coding environment.

(You can register with your GitHub account here with just one-click)

Loom

With Loom you’ll be able to quickly take screen recordings, and use it to share your code and relevant bugs with your mentors/instructors and the rest of the team and present your assignments and applications.

When recording using Loom, try to zoom in as much as possible on the application you are using, e.g. code editor, terminal, the browser, etc. in order for the instructors to have a clear and sharp view of your window.

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack? Search for: Kostas Minaidis (kostasx)
Updated: 25.10.2020

Setting up Ubuntu/Windows Dual-Boot


IMPORTANT: You can skip this lesson.

Read this entire section before starting

Dual-booting provides two operating systems on your computer that you can switch between with a simple reboot. One OS will not modify the other unless you explicitly tell it to do so. Before you continue, be sure to back up any important data and to have a way to ask for help. If you get lost, scared, or stuck, we’re here to help in the Slack forum.

Step 1: Download Ubuntu

First, you need to download the version of Ubuntu you want to install on your computer. Ubuntu comes in different versions ("flavors"), but we suggest the standard Ubuntu. If you’re using an older computer, we recommend Xubuntu. Be sure to download the 64-bit version of Ubuntu or Xubuntu.

Step 2: Create a Bootable Flash Drive

Next, follow this guide to create a bootable flash drive so that you can install Ubuntu on your hard drive. If you don’t have a flash drive, you can also use a CD or DVD.

Note: You can use this method to try out different flavors of Ubuntu if you’d like. These images allow you to try out different flavors without committing to an installation. Be aware that running the OS from a flash drive will cause the OS to be slow and can decrease the life of your flash drive.

Step 3: Install Ubuntu

Step 3.1: Boot from the Flash Drive

First, you need to boot Ubuntu from your flash drive. The exact steps may vary, but in general, you will need to do the following:

  • Insert the flash drive into the computer.
  • Reboot the computer.
  • Select the flash drive as the bootable device instead of the hard drive.

For example, on a Dell computer, you would need to plug in the flash drive, reboot the computer, and press the F12 key while the computer is first booting up to bring up the boot menu. From there, you can select to boot from the flash drive. Your computer may not be exactly the same, but Google can help you figure it out.

Step 3.2: Install Ubuntu

If you would like to test out the version of Ubuntu on the flash drive, click ‘Try me’. When you have found a flavor of Ubuntu you like, click ‘Install’ and continue to the next step.

Installing Ubuntu is where the real changes start happening on your computer. The default settings are mostly perfect, but be sure to "Install Ubuntu alongside Windows" and change the allocated disk space allowed for Ubuntu to 30 GB (or more if you can).

For step-by-step instructions, please follow this installation guide from the creators of Ubuntu.

A note to those who are wondering why they’re being asked to install an entire new operating system

Why is everyone ‘forced’ to switch to Linux or macOS for development? Are there no web developers out there who use Windows as their main operating system?

The answer to that question is: well, not that many. One of the reasons is that Ruby (on Rails) and Node.js, popular backend technologies taught by The Odin Project and widely used in the larger web development community, are open source projects that explicitly expect to run on an open-source (UNIX-based) platform. And while Apple’s operating systems have all included the XNU kernel, originally based on the FreeBSD flavor of UNIX since the transition from System 9 to Mac OS X in 2001, Microsoft has only recently commited to embracing open source and providing more support for the way people approach web development today.

One of the biggest features added in Windows 10 was the Windows Subsystem for Linux (WSL), which is a Linux command line within Windows. Setting up a development environment inside WSL is not beginner friendly, though, which is why we choose not to recommend and/or support this approach. All instructions you encounter here will assume you’re running either MacOS or Linux. Using WSL with these instructions may cause problems we are not able to help you resolve.

We do have great support for Linux/MacOS if you get stuck, so please give it a shot!

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack? Search for: Kostas Minaidis (kostasx)

UPDATED: 21.12.2020

Soon to be announced…

Conclusion

That was quite a journey. Take a second and reflect on the fact that you’ve just learned the basics of at least three different languages and, if you had to, you could probably hack together a web page on your own already.

You should be fairly comfortable typing commands into your computer’s command line and you should understand what happens when you enter a web address into your browser and it returns a functioning page. You should be able to create a basic web page and make it do some basic things with JavaScript. You should understand the purpose of backend code and how frameworks make it easier to write clean and maintainable code. Finally, you should have a clear understanding of how all this fits together in your future as a builder of web applications.

With what you know already, you could start putting together some basic websites or strike out to increase your knowledge on your own. However, we’re here to help you get a lot further than that, to the point where you can confidently build a full-featured and scalable web application, whether on your own or working as a developer in a top-tier tech company.

You’ve come a long way up the learning curve but there is so much more cool stuff that you’ll learn to do!

Buckle up, because this is only the beginning. Now it’s time to delve deeper into the areas covered by Web Dev 101. There are some fantastic projects in the courses that follow which will challenge you to the limit, but you’ll come out the other side ready to go and make your mark in the programming world.

The journey has just begun!

Conclusion

At this point, you should have a deep and nuanced understanding of not just how Javascript works but how you can use it with all the other knowledge you’ve gained so far to build exceptional web applications.

If you find something you don’t know or aren’t quite sure about, you should be a pro by now at Googling your way to an answer, looking at docs, and cruising through Stack Overflow posts. You’ve got all the tools you need to be a developer. And, really, the big secret is that you’ve been a web developer for a long time already.

So where do you go from here? BUILD! Build and build and build and build (see a theme in this curriculum yet?). Use what you’ve learned to create great projects. Get a job so someone else pays you to build. But focus on creating interesting software and using that to drive your education.

There’s a whole world of additional things you can learn — D3 for data visualization, other full-stack frameworks or single-page MVC front-end frameworks… all that stuff is best learned when you’ve got something you want to build that requires "the perfect tool for the job."

And speaking of jobs, if you’ve made it this far then you’ve displayed the kind of capability and drive that employers are looking for. The final step is to show that to the world and get them to pay you to keep learning.

Additional Resources


Material based on Erik Trautman | The Odin Project

Feedback

  • Is there anything we can help with up to this point? Do you have something to suggest about this chapter? Let us know in the comments below.

UPDATED: 01.02.2021