Web APIs – event listening and mouse events

1. Event monitoring

What is an event?

Events are actions or things that happen within the system while programming

For example, a user clicks a button on a web page

What is event listening?

It is to let the program detect whether an event occurs. Once an event is triggered, it immediately calls a function to respond, which is also called a binding event or a registered event. For example, a drop-down menu is displayed when the mouse passes over it, and a carousel image can be played by clicking on it, etc.

1.1 Basic syntax

Element object.addEventListener(‘event type’, function to be executed)

Three elements of event monitoring:

  • Event source: The DOM element was triggered by the event. To obtain the DOM element
  • Event type: How to trigger it, such as mouse click, mouse over, etc.
  • Function called by event: what to do
<body>
    <button>Click</button>
    <script>
        // Requirement: When the button is clicked, a dialog box pops up
        // 1. Event source button
        const btn = document.querySelector('button')
        btn.addEventListener('click',function(){
            alert('What to eat today?')
        })
        // 2. Event type mouse click
        // 3. Event handler pops up dialog box
    </script>
</body>

1.1.1 Event Type

The mouse passes and the mouse leaves

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 200px;
            height: 200px;
            background-color: blue;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        const div = document.querySelector('div')
        //mouse passes
        div.addEventListener('mouseenter',function(){
            console.log('I'm here')
        })
        //mouse leaves
        div.addEventListener('mouseleave',function(){
            console.log('I'm gone')
        })
    </script>
</body>
</html>

1.2 Exercise

JD.com click to close the top advertisement

Requirement: After clicking to close, the top will close

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      position: relative;
      width: 1000px;
      height: 200px;
      background-color: pink;
      margin: 100px auto;
      text-align: center;
      font-size: 50px;
      line-height: 200px;
      font-weight: 700;
    }

    .box1 {
      position: absolute;
      right: 20px;
      top: 10px;
      width: 20px;
      height: 20px;
      background-color: skyblue;
      text-align: center;
      line-height: 20px;
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="box">
    I am an advertisement
    <div class="box1">X</div>
  </div>
  <script>
    // 1. Get the event source
    const box1 = document.querySelector('.box1')
    // Close the big box
    const box = document.querySelector('.box')
    // 2. Event listening
    box1.addEventListener('click', function () {
      box.style.display = 'none'
    })
  </script>
</body>

</html>

2. Extended reading-event monitoring version

2.1 Event listening version

DOM L0

Event source.on event = function(){}

DOM L2

Event source.addEventListener(event, event handling function)

Difference: the on method will be overwritten, and the addEventListener method can be bound multiple times and has more event features.

Development history:

  • DOM L0: is the first version of DOM development; L: level
  • DOM L1: DOM level 1 became a W3C recommended standard on October 1, 1998
  • DOM L2: Register events using addEventListener
  • DOM L3: The DOM3 level event module redefines these events based on DOM2 level events and also adds some new event types.

3. Random roll call case

analyze:

  1. Click the start button to randomly extract a piece of data from the array and put it on the page
  2. Click the end button to delete a data currently extracted from the array
  3. When the last data is extracted, both buttons are disabled at the same time (at the beginning of writing, only the last data is left and does not need to be extracted)

Core: Use the timer to display quickly, stop the timer to end the display

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        h2 {
            text-align: center;
        }

        .box {
            width: 600px;
            margin: 50px auto;
            display: flex;
            font-size: 25px;
            line-height: 40px;
        }

        .qs {

            width: 450px;
            height: 40px;
            color: red;

        }

        .btns {
            text-align: center;
        }

        .btns button {
            width: 120px;
            height: 35px;
            margin: 0 50px;
        }
    </style>
</head>

<body>
    <h2>Random roll call</h2>
    <div class="box">
        <span>The name is:</span>
        <div class="qs">Display name here</div>
    </div>
    <div class="btns">
        <button class="start">Start</button>
        <button class="end">End</button>
    </div>

    <script>
        //data array
        const arr = ['Ma Chao', 'Huang Zhong', 'Zhao Yun', 'Guan Yu', 'Zhang Fei']
        //Global variables of the timer
        let timerId = 0
        // The random number requires a global variable
        let random = 0
        // Business 1. Start button module
        const qs = document.querySelector('.qs')
        // 1.1 Get the start button object
        const start = document.querySelector('.start')
        // 1.2 Add click event
        start.addEventListener('click',function(){
            timerId = setInterval(function(){
                // random number
                random = parseInt(Math.random() * arr.length)
                // console.log(arr[random]);
                qs.innerHTML = arr[random]
            },35)

            // If there is only one value in the array, there is no need to extract it. Just disable the two buttons.
            if(arr.length === 1){
                // start.disabled = true
                // end.disabled = true
                strat.disabled = end.disabled = true
            }

        })

        // 2. Close button module
        const end = document.querySelector('.end')
        end.addEventListener('click',function(){
            clearInterval(timerId)
            // It's over, you can delete the currently extracted array element
            arr.splice(random,1)
            console.log(arr);
        })

    </script>
</body>

</html>