JavaScript (15) – Events

Time:2022-4-28

Event profile

Event: it refers to some specific interaction moments in the document or browser window. For web applications, there are the following representative events: clicking on an element, moving the mouse over an element, closing a pop-up window, and so on.

JavaScript is based onEvent driven as the coreA language. The interaction between JavaScript and html is realized through events.

Three elements of events

Three elements of events: event source, event and event driver

For example, when I press the switch with my hand, the light comes on. In this case, the source of the event is: hands. The event is: press the switch. The event driver is: the light is on or off.

For another example, when an advertisement pops up on the web page, I click the X in the upper right corner, and the advertisement is closed. In this case, the event source is X. The event is: onclick. The event driver is: the advertisement is turned off.

So we can sum up: who triggered the follow-up event, who is the event source.

The summary is as follows:

Event source: the HTML tag that raises subsequent events.

Event: JS has been defined (see the figure below).

Event drivers: operations on styles and HTML. That is, DOM.

In other words, we can write some JS code in the attribute corresponding to time. When the event is triggered, these codes will be executed.

The code writing steps are as follows:(important)

(1) Get event source: document getElementById(“box”); / / similar to findviewbyid in Android

(2) Binding event: event source box Event onclick = function() {event driver};

(3) Writing event drivers: operations on DOM.

The simplest code example: (click box1, and then pop up the box)

<body>

<di vid=”box1″></div>

<scripttype=”text/javascript”>

//1. Get event source

var div=document.getElementById(“box1”);

//2. Binding events

div.onclick=function() {

//3. Write event driver

Alert (“I am the pop-up content”);

   }

</script>

</body>

Common events are as follows:

JavaScript (15) - Events

The following describes the three elements of this event.

1. How to obtain the event source (DOM node acquisition)

Common ways to get event sources are as follows:

vardiv1=document. getElementById(“box1”);// Method 1: obtain a single label through ID

vararr1=document. getElementsByTagName(“div”);// Method 2: get the tag array through the tag name, so there is s

vararr2=document. getElementsByClassName(“hehe”);// Method 3: get the tag array through the class name, so there is s

2. How to bind events

Method 1: directly bind anonymous functions

<divid=”box1″></div>

<scripttype=”text/javascript”>

vardiv1=document.getElementById(“box1”);

//The first way to bind events

div1.onclick=function() {

Alert (“I am the pop-up content”);

   }

</script>

Method 2: define the function separately before binding

<divid=”box1″></div>

<script type=”text/javascript”>

var div1=document.getElementById(“box1”);

//The second way to bind events

div1. onclick=fn;// Note that this is FN, not FN (). FN () refers to the return value.

//Define functions individually

functionfn() {

Alert (“I am the pop-up content”);

   }

</script>

Note the comments above.When binding, write FN instead of FN ()。 FN represents the entire function, while FN () represents the return value.

Method 3: inline binding

<!– Inline binding — >

<divid=”box1″onclick=”fn()”></div>

<scripttype=”text/javascript”>

functionfn() {

Alert (“I am the pop-up content”);

   }

</script>

Note that in the first line of code, when binding, it is written as “FN ()”, not as “FN”. Because the binding code is not written in JS code, but is recognized ascharacter string

3. Event driver

We take alert as an example above. Not only that, we can also manipulate the attributes and styles of tags. Examples are as follows:

When you click the mouse, the original pink div becomes larger and the background becomes red:

<style>

#box1{

width:100px;

height:100px;

background-color:pink;

cursor:pointer;

       }

</style>

</head>

<body>

<divid=”box1″></div>

<scripttype=”text/javascript”>

vardiv1=document.getElementById(“box1”);

//When you click the mouse, the original pink div becomes larger and the background becomes red

div1.onclick=function() {

div1. style. width=”200px”;// Attribute values should be written in quotation marks

div1.style.height=”200px”;

div1. style. backgroundColor=”red”;// The property name is backgroundColor, not background color

   }

</script>

Precautions for the above code:

When writing attribute values in JS, use quotation marks

When writing the attribute name in JS, it is the background color, not the background color in CSS.

The results are as follows:

JavaScript (15) - Events

Onload event

The onload event is special. Let’s talk about it separately.

When the page is loaded (text and picture), the onload event is triggered.

give an example:

<scripttype=”text/javascript”>

window.onload=function() {

console. log(“smyhvae”);// When the page is loaded, print the string

   }

</script>

One thing we need to know:JS is loaded synchronously with HTML。 Therefore, if an element is used, it is easy to report an error before defining the element. At this time, the onload event can come in handy. We can put the code using the element in onload to ensure that this code is the last execution.

The suggestion is: execute JS content after all elements on the whole page are loaded. So, window Onload prevents the use of tags before they are defined.

remarks: the onload event will be explained and exemplified in more detail in the next article “24-dom introduction and DOM operation”.

Event example: Jingdong top advertising column

JavaScript (15) - Events

For example, in the above figure, when the mouse clicks the X in the upper right corner, the whole advertising column will be closed, which requires events.

The code implementation is as follows:

<!DOCTYPE html>

<html>

<headlang=”en”>

<metacharset=”UTF-8″>

<title></title>

<style>

       * {

padding:0;

margin:0;

       }

.top-banner{

background-color:pink;

height:80px;

       }

.w{

width:1210px;

margin:10pxauto;

position:relative;

       }

img{

display:block;

width:1210px;

height:80px;

background-color:blue;

       }

a{

position:absolute;

top:5px;

right:5px;

color:#fff;

background-color:#000;

text-decoration:none;

width:20px;

height:20px;

font:70014px/20px”simsum”;

text-align:center;

       }

.hide{

display:none!important;

       }

</style>

</head>

<body>

<divclass=”top-banner”id=”topBanner”>

<divclass=”w”>

<imgsrc=””alt=””/>

<ahref=”#”id=”closeBanner”>×</a>

</div>

</div>

<script>

//Requirements: click the case to hide the box.

//Idea: click the a link to hide the top banner box (add the hidden class name).

//1. Get event source and related elements

varcloseBanner=document.getElementById(“closeBanner”);

vartopBanner=document.getElementById(“topBanner”);

//2. Binding event

closeBanner.onclick=function() {

//3. Write event driver

//Class control

//        topBanner. className += ” hide”; // Keep the original class name and add a new class name

topBanner. className=”hide”;// Replace the old class name (method 1)

//        topBanner. style. display = “none”; // Method 2: the effect is the same as that of the previous line of code

   }

</script>

</body>

</html>

Note the last line of code. This method will replace the old class name, which means that no matter what the previous class name is, it will be modified.

Examples of events:

Required effect: when the mouse hovers over the IMG, it will be replaced with another picture; When the mouse leaves, the original picture will be restored.

Code implementation:

<!DOCTYPE html>

<html>

<headlang=”en”>

<metacharset=”UTF-8″>

<title></title>

<script>

//window. Execute this code after the onload page is loaded

window.onload=function() {

//Requirement: put the mouse on img and replace it with another picture, that is, modify the path (SRC value).

//Steps:

//1. Get event source

//2. Binding event

//3. Write event driver

//1. Get event source

varimg=document.getElementById(“box”);

//2. Binding event (hover event: when the mouse enters the event source, the event will be triggered immediately)

img.onmouseover=function() {

//3. Write event driver (modify SRC)

img.src=”image/jd2.png”;

//                this.src = “image/jd2.png”;

           }

//2. Binding event (hover event: when the mouse enters the event source, the event will be triggered immediately)

img.onmouseout=function() {

//3. Write event driver (modify SRC)

img.src=”image/jd1.png”;

           }

       }

</script>

</head>

<body>

<imgid=”box”src=”image/jd1.png”style=”cursor: pointer;border: 1px solid #ccc;”/>

</html>