Absolute Beginner's Guide to Learn JavaScript, Part-3
Afroza Nowshin
Posted on August 21, 2022
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>
It will look like the following:
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>
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>
That's it. Now if we click the button, we will see that the text meow is now changed.
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>
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>
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>
The output should look like the following if you write a text and hit enter:
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>
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>
You can see the count 2 and 5 below:
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
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 = () => {
}
Or
() => {
}
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>
Output is shown after 10 seconds:
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>
You will see that the browser has Meow printed every 1 second:
That's a wrap for today. Hopefully, I will write about JavaScript Promise in the upcoming post. Till then, tata!
Posted on August 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 22, 2024