preface

In this era of frameworks, many people may have forgotten some of the basic methods of JS. While it’s (probably) rare to write native JS code in projects these days, I’ve heard the phrase, “The deeper you know, the higher you can get.” So the JS native API is something to be familiar with. This article summarizes the basic JS event binding and introduces three ways to bind events.

  • Bind directly in HTML
  • Bind in Javascript
  • Bind event listener function addEventListener()

methods

1. Specify it directly in HTML

For example, the mouse click event onclick, the double click event onmouseover, the mouse move event onmouseover, onmouseout. It can be divided into two kinds. ① Write directly in HTML attributes

<button onclick="alert('hello world')">Click</button>
Copy the code

② Custom functions in HTML

<button onclick="func()">Click</button>
<script type="text/javascript">
  var func = () => {
    alert('hello world')
  };
</script>
Copy the code

2. Bind in Javascript

The first method combines JS events with HTML tags, which is not conducive to project management and development. In order to keep the structure of the code clear, it is more efficient to separate it according to different functions.

<button id="btn">Click</button> <script type="text/javascript"> document.getElementById('btn').onclick = func; Function func() {alert('hello world'); function func() {alert('hello world'); } </script>Copy the code

3. Bind event listener function addEventListenr()

The second method is better than the first one, but it also has disadvantages. Sometimes more than one event is triggered on a click event. One idea is to add another layer of functions to the func() function, such as putting the defined functions A () and b() inside func(). But this is too cumbersome, so use addEventListenr()

(1) grammar

target.addEventListener(type, listener, options);

① Target is the object obtained by DOM manipulation

② Type indicates the event type. Examples include Click, mouseout

③ The listener here refers to the function that is executed when the event starts. You can either write the function name or define the function and enclose it in quotes.

④ Options Optional. See the reference link for details.

(2) instance

<button id="btn">Click</button> <script type="text/javascript"> const dom = document.getElementById('btn'); dom.addEventListener('click', func1); dom.addEventListener('mouseout', func2); function func1() { alert('hello') }; function func2() { alert('world') }; // Mouse click events and mouse away events are executed, printing hello, world </script> respectivelyCopy the code