DEV Community

Cover image for Absolute Beginner's Guide to Learn JavaScript, Part-3
Afroza Nowshin
Afroza Nowshin

Posted on • Updated on

Absolute Beginner's Guide to Learn JavaScript, Part-3

Over the course of this series "Start with Me", I am writing about the heavily used concepts of JavaScript that as a web-developer, you are expected to know. I am giving the tools in my posts so that you can feel less overwhelmed while it comes to build the UI and UX, or adding different functionalities in the website.

If you followed till now, you know about the DOM trees of a web page and how to access the objects of the trees, how to debug your code by writing messages and types in console.log() , how to manipulate arrays and objects with various methods etc. Today, we will learn how to handle the events that needs handling, or “Event Handling” in JavaScript, what is “this” keyword, arrow functions and how to set an interval or timeout for a specific action in JavaScript. Let’s get to it.

6. Event handling

In the first post I talked about HTML elements. Think about an element, button. What do you do with a button in a website? You either use it to submit something or click it to see something. Let’s write a code to put a button in a web page:

<!DOCTYPE html>
<html>

<body>

    <h1>Event Handling</h1>
    <div>
        <button>Click me!</button>
    </div>
</body>
<script>


</script>

</html>

Enter fullscreen mode Exit fullscreen mode

It will look like the following:

Output 1

Nothing will happen if you click the button, because it's a static HTML element. We need to do something about it. How about if we click, we will change the text of the paragraph below, to "Hello World"?

How to do that?

Clicking the button is an event, therefore we have to attach an action to this event which will handle the event of clicking the button. We will write a function in JavaScript named clickFunc like the following:

...
<script>

function clickFunc(){
      document.getElementById("paragraph").innerHTML = "Hello World"
}

</script>

Enter fullscreen mode Exit fullscreen mode

The onclick event occurs when the user clicks on the button element. In order to do this, in the button event we will write in the onclick property:

...

    <div>
           <button onclick="clickFunc()">Click me!</button>
        <p id="paragraph">meow</p>
    </div>
</body>
...

</html>

Enter fullscreen mode Exit fullscreen mode

That's it. Now if we click the button, we will see that the text meow is now changed.

Output 2

Event Handling means dealing with the events that the HTML elements can cause in a web page. HTML elements need JavaScript to handle their events. If you think of ordering food online when you are hungry, that is an event handling. Being hungry is your event, and to handle this event you are ordering food online.

You could write the following code in another way, with addEventListener() method. This method takes an event and a function and attaches an event handler to an element. The code will be like the following:


<!DOCTYPE html>
<html>

<body>

    <h1>Event Handling</h1>
    <div>
        <button id="btn">Click me!</button>
        <p id="paragraph">meow</p>
    </div>
</body>
<script>

const element = document.getElementById("btn");
element.addEventListener("click", function() {
  document.getElementById("paragraph").innerHTML = "Hello World";
});

</script>

</html>

Enter fullscreen mode Exit fullscreen mode

Notice how there's no name of function that we wrote here. It's an anonymous function, meaning "A function has no name".

Let's handle another event; text change in the input box. Put an input element in the web page like the following:

<body>

    <h1>Event Handling</h1>
    <div>
       <input type="text 
                      onchange="changeFunc(this.value)" value=""/>

        <p id="paragraph"></p>
    </div>
</body>

Enter fullscreen mode Exit fullscreen mode

The event that we will be handling now is "onchange". We will write a function that will take whatever we write in the box and print in the paragraph tag beneath. The text we will write will be captured via the value property of input tag, as a result, we are passing the value in the changeFunc function as an argument. Notice that we wrote "this.value" instead of value as the argument. We will talk about what this means in the following section of this post.

Now, let's write the changeFunc body:

function changeFunc(val){
    document.getElementById("paragraph").innerHTML = val
}

</script>

Enter fullscreen mode Exit fullscreen mode

The output should look like the following if you write a text and hit enter:

Output 3

These are some of the most used event handling in JavaScript. Refer to this link of W3Schools to see the list of events. If you want to learn more, you can read this blog of Eloquent JavaScript.

7. this keyword, bind() method and Getting Smart with ES6:

In the previous section, we saw "this.value" as an argument. this keyword refers to an object in JavaScript. What does that mean? Well, this attaches itself to the way it is being used. In our context, we wanted the text that we wrote in input element. Writing something in input is an event, and here this refers to the element that received the event. Input element received our text event in its value property, therefore we wrote this.value as the function argument.

Usually, this refers to the global object, and it's also true in the case of a function. In an object method, this refers to the object.

Let's write an object that has the count of your animals:


const animal = {
    "cat": 2,
    "dog": 5,

  }


}

</script>

Enter fullscreen mode Exit fullscreen mode

We then write an object method that will show the count in the paragraph tag:


const animal = {
    "cat": 2,
    "dog": 5,
    count : function() {
    return this.cat + " " + this.dog;
  }


}
document.getElementById("paragraph").innerHTML = animal.count();

</script>

Enter fullscreen mode Exit fullscreen mode

You can see the count 2 and 5 below:

Output 6

So far, we have learned what this means. This can refer to an object or a function. In order to bind a specific object or function which has its own this, to another entity, we use bind() method in JavaScript.

I think I have come across the best explanation about bind() from this stackoverflow link - What is bind() in JS. Based on an answer which has 89 upvotes, I used bind() to bind an object with a function like the following:


var ourFunc = function(value){
    console.log(this[value])
}

var obj = {
    x : 5,
    y : 10
};

obj.log = ourFunc.bind(obj)

obj.log('x')  // Output: 5

Enter fullscreen mode Exit fullscreen mode

JavaScript has a major revision in ES6 which stands for ECMAScript 6. The foundation of React JS is on ES6. In ES6 the function is written as an arrow function like the following:


hello = () => {

}
Enter fullscreen mode Exit fullscreen mode

Or


() => {

}
Enter fullscreen mode Exit fullscreen mode

This syntax is concise, and if you use {} you do not have to write "return" to return something. This arrow function is not hoisted, which means it must be defined before it is used. Another interesting fact is, arrow function doe not have this attached, which makes it not suitable for object methods, otherwise, it's my go to way to define functions in React JS because I don't have to worry about binding. ES6 ups your game once you master Vanilla JS and move on to learning a JavaScript framework. This link covers the basics of ES6 if you want to learn more - W3Schools

8. setTimeout() and setInterval()

Sometimes, it may so happen that you want to run a particular piece of your code or a function to run for a certain time. That's when you use setTimeout() method. The first parameter is the code or the function, and the second parameter is the amount of time after you which the execution stops. Time is calculated in milliseconds so 1 second = 1000 miliseconds.


<script>

const timeout = setTimeout(hello, 10000);

function hello(){
    document.getElementById("paragraph").innerHTML = "Hello World"
}

</script>

Enter fullscreen mode Exit fullscreen mode

Output is shown after 10 seconds:

Output 9

There is another method named setInterval(), which is used to execute something after the time in milliseconds that is passed in it. If you run the following code:


<script>

const interVal = setInterval(hello, 10000);

function hello(){
    document.getElementById("paragraph").innerHTML += "Meow"
}

</script>

Enter fullscreen mode Exit fullscreen mode

You will see that the browser has Meow printed every 1 second:

Output 10

That's a wrap for today. Hopefully, I will write about JavaScript Promise in the upcoming post. Till then, tata!

Top comments (1)

Collapse
 
afrozansenjuti profile image
Afroza Nowshin

Thank you so much! 🥲