SoFunction
Updated on 2025-03-01

3 examples of JS binding events (simple and easy to understand)

Preface

I believe everyone has understood events, but how to bind events to elements and how to use them?

Let me introduce three ways to bind events!

The following are all examples using click events (click)

1. In-line binding events

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <!-- The first method,In-line binding events,Take a function name -->
    <button onclick="fun()">Click</button>
</body>
<script>
    // The first method    function fun() {
        (1);
    }
</script>
</html>

2. Use on binding events

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <button>Click</button>
</body>
<script>
    // The second method    // Get the button element first    let but = ("button")
    //Bind using on method     = function(){
        (1);
    }
</script>
</html>

3. Use event listening to bind events

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <button>Click</button>
</body>
<script>
    // The third method    // Get the button element first    let but = ("button")
    // Use addEventListener    ("click",function(){
        (1);
    })
</script>
</html>

Code summary:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Three ways to bind events</title>
</head>
<body>
      <!-- The first method,In-line binding events,Take a function name -->
      <!-- <button οnclick="fun()">Click</button> -->
      <button>Click</button>
</body>
<script>
     // The first method    //  function fun() {
    //     (1);
    // }
    // .......................
     // The second method    // Get the button element first    // let but = ("button")
    //Bind using on method    //  = function(){
    //     (1);
    // }
    // ...........................
     // The third method    // Get the button element first    // let but = ("button")
    // Use addEventListener    // ("click",function(){
    //     (1);
    // })
</script>
</html>

Summarize

This is the end of this article about 3 methods of JS binding events. For more related JS binding event methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!