loading...

A Beginners Guide to JS Events

scdan0624 profile image SCDan0624 ・4 min read

Intro
As a beginning web developer you may want the user to be able to interact with your web page. This is where HTML/JS events are useful. With a few lines of code you can have messages be displayed to users or form information being submitted. In this short tutorial you will learn what these events are and some of the cool things you can do with them.

What is a HTML/JS Event?

An HTML event is when something happens to an HTML element. This event can be something the browser does, or something a user does. When you add Javascript to the HTML pages they can react to the events. These reactions can trigger various different effects such as something blurring, changing color, being deleted, being added, and much much more.

How to code an event reaction
There are a few ways to trigger these events. For this beginners guide we will focus on two: using event attributes and addEventListener.

Using Event Attributes
To use event attributes we use the following code

<element event='some JavaScript'>
Enter fullscreen mode Exit fullscreen mode

For example what is you wanted to change your text with a click?

Copy and past the code below into an HTML file:

<!DOCTYPE html>
<html>
<body>

<p id="demo" onclick="myFunction()">Click me to change my text color.</p>

<p>A function is triggered when the p element is clicked. The function sets the color of the p element to blue.</p>

<script>
function myFunction() {
  document.getElementById("demo").style.color = "blue";
}
</script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Now open this HTML file in your browser. If you hover your mouse over the text that says Click me to change my text color, and click your mouse the text will change from black to blue. This is the power of HTML/JS events!

Using addEventListener

Another way to trigger an event is through addEventListener. The syntax for addEventListener is the following:

document.addEventListener(event, function, useCapture)
Enter fullscreen mode Exit fullscreen mode

Using the code below before we will change change the color of some text using an addEventListener:

<html>
<body>

<p>This example uses the addEventListener() method to attach a click event to the document.</p>

<p>Click anywhere in the document.</p>

<p><strong>Note:</strong> The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.</p>

<p id="demo">Hello</p>

<script>
document.addEventListener("click", function(){
   document.getElementById("demo").style.color = "red";
});
</script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

By clicking on the document we change the Hello from black to red text.

Changing color of text is the tip of the iceberg here are some other cool things you can do with HTML/JS events.

Other JS/HTML events

For the next examples we will be using the following HTML file. Create a index.js file and code all the events in that file.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    input {
      font-size: 2rem;
    }
  </style>
</head>

<body>
  <div class="container">
    <div id="image_content">
        <img src="" id="image" data-id=""/>
         <span id = "likes2">Likes:
            <span id="likes"></span>
        </span>
        <button id="like-button">Like</button>
        <form id="comment_form">
            <input id="comment-input" type="text" name="comment" placeholder="Add Comment"/>
            <input type="submit" value="Submit"/>
        </form>
        <ul id="comments"></ul>
        <h1></h1>
    </div>
  </div>
  <script type="text/javascript" src='index.js'></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Keypress to Add New Text

Add the following code to your index.js file.

const likesTag = document.getElementById('likes');

document.addEventListener("keypress", function(){
    const h1 = document.createElement('h1')
    likesTag.append(h1)
    h1.innerText = "One key press adds a new line of text";
});
Enter fullscreen mode Exit fullscreen mode

Now whenever you press a button on your keyboard the one keypress adds a new line of text will show up on your page.

MouseOver to Send an Alert

Erase your keypress event listener from the previous lesson. Replace it with the following code:

const liked = document.getElementById('likes2');

liked.addEventListener("mouseover", function(event){
    alert('Hey keep your mouse pointer to yourself');
});

Enter fullscreen mode Exit fullscreen mode

By creating a liked variable first we can then attach it to the addEventListener, while still making it available for future functions.

Now when you hover your mouse over the likes text you should see the following:

Alt Text

Removing Events
Now that we know how to add events what if we want to remove the events as well? This is where removeEventListener is a great tool.

The syntax for removeEventListener is very similar to addEventListener:

 element.removeEventListener(event, function, useCapture)
Enter fullscreen mode Exit fullscreen mode

Example

Copy the following code to a new html file.

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
  background-color: blue;
  border: 1px solid;
  padding: 50px;
  color: white;
}
</style>
</head>
<body>

<div id="myDIV">This div element has an click event handler that displays a random number whole number between 1 and 100, every time you click your mouse inside this blue field.
  <p>Click the button to remove the DIV's event handler.</p>
  <button onclick="removeHandler()" id="myBtn">Stop Event</button>
</div>

<p><strong>Note:</strong> The addEventListener() and removeEventListener() methods are not supported in Internet Explorer 8 and earlier versions.</p>

<p id="demo"></p>

<script>
document.getElementById("myDIV").addEventListener("click", myFunction);

function myFunction() {
  document.getElementById("demo").innerHTML = Math.floor(Math.random() * 100);
}

function removeHandler() {
  document.getElementById("myDIV").removeEventListener("click", myFunction);
}
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now open this file in your browser, (In VScode right click on code and click open in default browser). Your browser should look like this:

Alt Text

Bring your mouse cursor over the blue area and click down. You will see a random number between 1 - 100 appear at the bottom. Keep clicking and a new random number will appear.

Now head over to the stop event button and click. This will trigger the removeEventListener. Now go back to the blue with your cursor and click again. As you can see the random number generator has stopped completely.

Conclusion
Now that you have learned some basic HTML/JS events you will be able to enhance your web page easily and effectively. There are numerous more events than the few examples shown here. Here is a link to the entire list:

http://help.dottoro.com/larrqqck.php

Discussion

pic
Editor guide