Chat with Thomas | Profile

Welcome to the Modern Web Design.

📖 Lecture 3—Functions and Events Handling

This is lecture 3 of the Beginning jQuery course. In this lecture, we focus on the JavaScript function and jQuery events handling methods.

If you come across any questions, feel free use the chat to ask me.

Understanding Function

If you’re new to JavaScript function, I suggest to get started reading the reference from Mozilla Developer Network.

After you understand the function, I recommend reading this chapter from the Eloquent JavaScript book.

Understanding the this in JavaScript

When we are inside a function, sometime we may want to refer to the current context by using the special variable this. But what is the thisactually pointing to?

A simple rule is JavaScript’s this refers to the one that calls the function. For example:

function foo() {
}; // `this` refers to window.
var objectA = {
  hello: function(){
objectA.hello(); // `this` refers to `objectA`.; // ** `this` refers to `window`.
  console.log(this);  // `this` refers to the $('#input').

** Note that we can use the call or apply method to change the context of any function calling

In other common object-oriented language, this ofter refers to the same instance. In JavaScript, the this refers to the context that calls that function.

Please make sure you read the Mozilla Developer Network’s this reference and understand the detail on how this works.

Advance: Object and Prototype

Once you fully understand how function works, I recommend reading the Object chapter from the Eloquent JavaScript book. It shows you how we can manage objects in object oriented way.

Event handling

Handling events is one of the most common tasks when writing jQuery. We often need to respond to user’s actions and provide appropriate feedbacks. The following jQuery’s events handling documentation provides a getting started guide.

<a href="


The delegate method.

<a href="

<a href="

Looping with jQuery each

In some cases, we need to loop through all the selected elements and apply logic on it. We can use the each method.

Usage example:

  // each of the matched element

Setting and Getting HTML attributes

There are prop and attr methods. Both methods access the attribute of the selected HTML tag. We prefer prop most of the time, as explained in this StackOverflow answer

Example—Inputing multiple names

Screenshot of the example

I created an example that demonstrates the techniques listed in this lecture. It is a list of inputs that user input names into it. User can add more inputs by clicking the “+” button. There is a confirmation dialog when submitting the form.

<a href="


After going through the links and code examples listed in this lecture, you should be able to handle different events.

Thomas Mak