What is the event in JavaScript?

This article mainly introduces what is in JavaScript, has a certain reference value, and friends needed can be referred to. I hope that everyone has a big gain after reading this article. Let’s take a look at you with everyone.

In this article, we will discuss event handler, event listeners, and event objects. We will also introduce three different ways of processing events, as well as some of the most common events. By understanding events, you will be able to provide users with more interactive web experiences.

The event is an operation that occurs in the browser, which can be initiated by the user or the browser itself. Here are some common events that happen on the website:

page completes loading
  • User Click on a button
  • The user hovers in the drop-down list
  • User submission form

  • The user presses the keys on the keyboard

  • By encoding the JavaScript response executed on an event, the developer can display messages, verify data, and perform multiple other operations to the user.

  • Event handler and event listener

When the user clicks or pressing a key, an event will be triggered. These are called clicking events or button events, respectively.

An event handler is running a JavaScript function running in an event. An event listener adds an element of a response interface that allows specific elements to wait and “monitor” given event triggers.

There are three methods allocated to the element:

Inline event handler

Event handler property

  • We will detail these three methods to ensure that you are familiar with each method of triggering events, then discuss each method excellentshortcoming.
  • In-line event handler property

To start learning the event handler, we first consider the inline event handler. Let us start from a very basic example, consisting of a button element and a P element. We want the user to click the button to change the text content of the P.


Let’s start with an HTML page with a button. We will reference a JavaScript file that we will add the code later.

Events


Click ME

TRY TO

     On the button, we will add an attribute called OnClick. The attribute value will be a function we have created as chantext ().    Events    Click ME 

Try to Change Me. Let us create an Events.js file, which is located here in the JS / directory here. In this, we will create a ChangeText () function that will modify the textContent of the P element.
// Function to modify the text content of the paragraphconST CHANGETEXT = () => {const p = Document.QuerySelector (‘p’); p.TextContent = “i change Because of an inline Event handler.”;}

for the first time Load Events.html, you will see the page as shown below:
  However, when you or other user click the button, the P-marked text will be from Try To Change ME is changed to. I changed because the inline event handler.     The inline event handler is a direct method of starting understanding of the event, but usually should not exceed testing and educational purposes.   You can compare the inline event handler with the inline CSS style on the HTML element. Maintaining a separate class style show more practical than in each element, just like maintaining the JavaScript processed through a separate script file instead of adding a handler to each element.   

The next step of the inline event handler is the event handler property. This is very similar to the inline handler, but we set the properties of the elements in JavaScript, not the properties in the HTML. The settings here are the same, but we no longer include onclick = "ChangeText ()" in the mark:

Click Me

  ... /  
Our function will remain similar, just now Need to access the Button element in JavaScript. We can simply accessOnclick, just like accessing the style or ID or any other element properties, then assign a function reference.

// function to modify the text content => {const p = document.queryselector (‘p’); p.TextContent = “i change Because } // add event handler as a property of the button elementconst button = document.queryselector (‘button’); button.onclick = ChangeText;

JavaScript中的事件是什么

Note: The event handler does not follow the CamelCase convention followed by most JavaScript code. Note that the code is onclick instead of onclick.

When you load a web page for the first time, the browser will display the following:

JavaScript中的事件是什么

Now, when you click this button, it will have one Similar effects:

Note that when the function reference is passed to the onclick property, we do not include parentheses because we didn’t call the function at the time, but only passed it. Quote.

The maintenanceability of the event handler property is slightly more preferably in the inline handler, but it still has some of the same obstacles. For example, attempting to set a plurality of separate onclick properties will result in override all attributes except for the last one, as shown below.

Const P = Document.QuerySelector (‘p’); consT Button = Document.QuerySelector (‘Button’); const chanter = () => {p.TextContent = “Will i change?”;} const alrttext = () => {Alert (‘Will i alert?’); } // Events can be overwrittenButton.onClick = ChangeText; Button.onClick = alertText;
In the above example, click the button only display a warning without changing P Text, because the Alert () code is the code that is finally added to the property.

After the inline event handler and event handler properties, let us turn to the event listener.
 Event Loker    AddEventListener () Accepts two forced parameters - the events and listener callback functions to be listened. 

The HTML of the event listener is the same as the previous example.

Click Me
i will change. …

 We will still use the previous The same ChangeText () function. We will attach the addEventListener () method to the button.   // Function to modify the teethxt content of the paragraphconst changeText = () => {const p = document.querySelector ( 'p'); p.textContent = "I changed because of an event listener.";} // Listen for click eventconst button = document. QuerySelector ('Button'); Button.addeventListener ('Click', ChangeText); 
Note that for the first two methods, the Click event is referred to as ONCLICK, but for an event listener It is called Click. Each event listener removes the word from words. In the next section, we will see examples of more other types of events.

When you reload the page with the JavaScript code above, you will receive the following output:

At first, the event listener looks Event handler properties is very similar, but they have some advantages. We can set multiple event listeners on the same element, as shown in the following example.

JavaScript中的事件是什么 Const P = Document.QuerySelector (‘p’); const button = document.QuerySelector (‘Button’); const chantext = () => {p.TextContent = “WILL I change? “;} Const alertText = () => {Alert (‘Will I alert?’);} // multiple listener can be addedTo the Same Event and ElementButton.addeventListener (‘Click’, ChangeText); Button.addeventListener (‘Click’, AlertText);

In this example, these two events will Trigger, once you click Exit Warning, provide a warning and modified text to the user.

Typically, anonymous function is used instead of a function reference on the event listener. The anonymous function is a function that is not named. JavaScript中的事件是什么

// An Anonymous Function On An Event ListenerButton.addeventListener (‘Click’, () => {p.TextContent = “Will i change?”;};

You can also use the RemoveEventListener () function to remove one or all events from the elements.

// Remove Alert Function from Button ElementButton.RemoveEventListener (‘Click’, AlertText);
  In addition, you can in the document and window Use AddEventListener () on an object.  The event listener is the most common and preferred method of processing events in JavaScript. 

JavaScript中的事件是什么 We have learned the inline event handler, event handler properties, and event listeners using the Click event, but there are also JavaScript More events. Below we will discuss some of the most common events.

Mouse event The mouse event is one of the most common events. They refer to events involving clicking on the button or hover and move the mouse pointer. These events also correspond to the equivalent operation on the touch device.

Description

  Click  When the mouse is pressed And release 

DBLClick

, when the element is clicked twice,

  MOUSEENTER  
When the pointer enters the element MOUSELEAVE

Trigger

JavaScript中的事件是什么 MOUSEMOVE when the pointer leaves one element

Whenever the pointer is moved

  , click is a composite event, composed of a combined mousedown and mouseup events, and press or lifts separately These two events will be triggered when the mouse button is entered. 
Create a hovering effect at the same time using MouseEnter and MouseEleave, as long as the mouse pointer stays on the element, the hover is continuous.

Form event

The form event is an operation related to a form, such as an input element being selected or unselected, and a form being submitted.
   
Describes

 Submit   Trigger when submitting a form
Focus

Triggers

BLUR

when the element (such as input) receives the focus Trigger when you lose the focus


When a element is selected, for example, the focus can be achieved by clicking or by the Tab key.

JavaScript is usually used to submit a form and send values ​​to backend languages. The advantage of sending a form using JavaScript is that the submission form does not need to be reloaded, and you can use JavaScript to verify the desired input field. Keyboard Events

Keyboard events are used to process keyboard operations, such as pressing a key, raising a key and holding a key.

KeyDown KeyPress is continuous when the key is keys Excitation The keyboard event has a specific attribute that accesses a single key. If a parameter called an event object is passed to an event listener, we can access more information about the operations that occur. Three attributes related to keyboard objects include Keycode, Key, and Code. For example, if the user presses the letter A key on the keyboard, the following attributes associated with the key will appear: attribute KEYCODE
Description
Press a key
Although they look very similar, KeyDown and KeyPress events cannot access all identical keys. KeyDown will confirm each key pressed, and KeyPress will omit the keys that do not generate characters, such as Shift, Alt or delete.

is related to the number.

65

Key

A

Code KeyCode attribute is one and it is pressed The key is related to the number. The key attribute is the name of the character, which can be changed – for example, pressing A with the SHIFT button to cause the key to a. The Code property represents the physical key on the keyboard. Note that Keycode is being discarded, preferably using code in new projects.

Indicates the pressed physical bile
Keya
In order to display this information through the JavaScript console, we can write the following code rows. // Test The Keycode, Key, And Code PropertiesDocument.addeventListener (‘KeyDown’, Event => {Console.log (‘Key:’ + Event.KeyCode); console. LOG (‘key:’ + event.key); console.log (‘code:’ + event.code);};
Once the Enter key is pressed on the console Now you can press the key on the keyboard, in this case, we will press A.
Event Object

The event object consists of attributes and methods that all events can be accessed. In addition to universal EVENT objects, each type of event has its own extension, such as KeyboardEvent and MouseEvent.

The EVENT object is transmitted to the inspectionPhotoelectric functions. It is usually written as Event or E. We can access the event’s Code property KeyDown to copy the keyboard control of the PC game. To try it, use the

tag to create a basic HTML file and load it into your browser.

Events Then type the following JavaScript code in the developer console in the browser. // Pass An Event Through To a ListenerDocument.addeventListener (‘Keydown’, Event => {Var Element = Document.QuerySelector (‘p’); // set variables for keydown Codes var a = ‘keya’; var s = ‘keys’; var d = ‘keyd’; var w = ‘keyw’; // set a direction for each code switch (event.code) {Case A: Element.TextContent = ‘Left’; Break; Case S: ​​Element.TextContent = ‘Down’; Break; Case D: Element.TextContent = ‘Right’; BreakCase W: Element.TextContent = ‘UP’; Break;}}); When you press a button -, A, S, D or W- you will see Similar to the following output: From here, you can continue to develop browser response methods and users who press these keys and create more dynamic websites. Next, we will introduce a most common event attribute: Target property. In the example below, our DIV has three elements in an interior. Events

One

TWO

Using an event. In the browser’s developer console, we can place an event listener on the external section element and get the nesting deepest element. Use an EVENT object, we can set the response associated with all events, including universal events and more specific extensions. Conclusion Event is an operation that occurs on the website, such as a click, hover, submit a form, load the page, or the keys on the keyboard. When we can let the website respond to the operation taken by the user, JavaScript becomes truly interactive and dynamic. Thank you for reading this article carefully, I hope that Xiaobian sharing in JavaScript is what content is helpful, and I also hope that everyone will support Tumi Cloud, pay attention to Tumi Yun Industry Information Channel, encounter The problem is looking for TUMI clouds, and the detailed solution is waiting for you to learn!
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment

const section = document.QuerySelector (‘section’); //print the successd targetsection.addeventListener (‘click “, event => {console.log (event.target); }); Click any of the elements to return the output of the relevant specific elements to the console using the Event.Target. This is useful because it allows you to place only an event listener that can be used to access many nested elements.