Day 4 - Web APIs

Learning objectives:

Ability to say 3-5 common keyboard events

Ability to know how to get which key the current keyboard is pressing

Know the browser's top object window

Ability to use window.onload events

Ability to use window.onresize events

Ability to tell the difference between two timers

Ability to complete jumps between pages using the href property of the location object

Be able to use the location object to get the parameter part of the url

Ability to refresh pages using methods provided by history

1.1. Common keyboard events

1.1.1 Keyboard Events

   <script>
        // Common keyboard events
        //1. Trigger when Keyup key pops up 
        document.addEventListener('keyup', function() {
            console.log('I bounce up');
        })
​
        //3. Key press triggers unrecognized function keys such as ctrl shift Left and right arrows
        document.addEventListener('keypress', function() {
                console.log('I pressed press');
        })
        //2. When the Keydown key is pressed, trigger recognizable function keys such as ctrl shift Left and right arrows
        document.addEventListener('keydown', function() {
                console.log('I pressed down');
        })
        // 4.The execution order of the three events keydown -- keypress -- keyup
    </script>

1.1.2 Keyboard Event Objects

 

 

Use the keyCode property to determine which key the user pressed

   
 <script>
        // The keyCode attribute in the keyboard event object gets the ASCII code value of the corresponding key
        document.addEventListener('keyup', function(e) {
            console.log('up:' + e.keyCode);
            // We can use the ASCII code value returned by keycode to tell which key the user pressed.
            if (e.keyCode === 65) {
                alert('The one you pressed a key');
            } else {
                alert('You did not press a key')
            }
        })
        document.addEventListener('keypress', function(e) {
            // console.log(e);
            console.log('press:' + e.keyCode);
        })
    </script>

1.1.3 Case: Simulate Jingdong key-in content

When we press the s key, the cursor is positioned in the search box (the text box gets the focus).

 

Note: Element object.focus() can be used to trigger a focus event

    
<input type="text">
    <script>
        // Get Input Box
        var search = document.querySelector('input');
        // Register keyup events for document
        document.addEventListener('keyup', function(e) {
            // Determine the value of keyCode
            if (e.keyCode === 83) {
                // Trigger Focus Event for Input Box
                search.focus();
            }
        })
    </script>

1.1.4 Cases: Simulating Jingdong Express Single Number Query

Requirements: When we enter content into a text box, the text box will automatically display large font size content on it.

 

 

   
 <div class="search">
        <div class="con">123</div>
        <input type="text" placeholder="Please enter your courier number" class="jd">
    </div>
    <script>
        // Get the element to operate on
        var con = document.querySelector('.con');
        var jd_input = document.querySelector('.jd');
        // Register keyup events for input boxes
        jd_input.addEventListener('keyup', function() {
                // Determine if the content of the input box is empty
                if (this.value == '') {
                    // Empty, hide enlarged reminder box
                    con.style.display = 'none';
                } else {
                    // Not empty, show enlarged reminder box, set the contents of the box
                    con.style.display = 'block';
                    con.innerText = this.value;
                }
            })
        // Register the Focus Loss Event for the Input Box and hide the Enlarged Tip Box
        jd_input.addEventListener('blur', function() {
                con.style.display = 'none';
            })
        // Register focus events for input boxes
        jd_input.addEventListener('focus', function() {
            // Determine if the content of the input box is empty
            if (this.value !== '') {
                // Show prompt box if not empty
                con.style.display = 'block';
            }
        })
    </script>

1.2. BOM

1.2.1. What is a BOM

The BOM (Browser Object Model) is the browser object model. It provides the object that interacts with the browser window independent of the content, and its core object is window.

BOM consists of a series of related objects, and each object provides many methods and properties.

BOM lacks standards, the standardization organization of JavaScript syntax is ECMA, the standardization organization of DOM is W3C, and BOM was originally part of Netscape browser standards.

 

1.2.2. Composition of BOM

BOM is larger than DOM and contains DOM.

 

1.2.3. Top Object window

 

1.2.4. Common events for windows objects

Page (Window) Load Events (2)

Type 1

 

window.onload is a window (page) loading event that is called when the document content is fully loaded and triggers the event (including images, script files, CSS files, and so on).

 

Type 2

 

When the DOMContentLoaded event is triggered, only when the DOM load is complete, excluding stylesheets, pictures, flash, and so on.

IE9 above support!!!

If there are many pictures on the page, it may take a long time for the user to access the onload trigger, and the interaction effect cannot be achieved, which will inevitably affect the user's experience. It is appropriate to use the DOMContentLoaded event at this time.

    
<script>
        window.addEventListener('load', function() {
            var btn = document.querySelector('button');
            btn.addEventListener('click', function() {
                alert('Click on me');
            })
        })
        window.addEventListener('load', function() {
            alert(22);
        })
        document.addEventListener('DOMContentLoaded', function() {
            alert(33);
        })
    </script>

Adjust Window Size Event

 

window.onresize is a handler that is called when a window is resized to load events.

Be careful:

  1. This event is triggered whenever the window size changes in pixels.

  2. We often use this event to complete a responsive layout. The current screen width of window.innerWidth

   
 <script>
        // Register Page Load Events
        window.addEventListener('load', function() {
            var div = document.querySelector('div');
            // Register resize window events
            window.addEventListener('resize', function() {
                // window.innerWidth Get Window Size
                console.log('Changed');
                if (window.innerWidth <= 800) {
                    div.style.display = 'none';
                } else {
                    div.style.display = 'block';
                }
            })
        })
    </script>
    <div></div>

1.2.5 Timer (two types)

The window object provides us with two very useful methods, timers.

  • setTimeout()

  • setInterval()

setTimeout() Bomb Timer

Turn on the timer

 

 

 

Common functions are called directly in code order.
​
Simple understanding: Callback means to call back. When the last thing is done, call back the function again.
For example, call functions in timers, event handlers, and callback functions.
​
Previously we talked about    element.onclick = function(){}    Or element.addEventListener("click", fn);    The function inside is also a callback function.
​

<script>
        // Callback function is an anonymous function
         setTimeout(function() {
             console.log('Time out');
​
         }, 2000);
        function callback() {
            console.log('Exploded');
        }
        // A callback function is a named function
        var timer1 = setTimeout(callback, 3000);
        var timer2 = setTimeout(callback, 5000);
    </script>

Case study: Close advertisement after 5 seconds

 

 

<body>
    <img src="images/ad.jpg" alt="" class="ad">
    <script>
        // Get the element to operate on
        var ad = document.querySelector('.ad');
        // Turn on the timer
        setTimeout(function() {
            ad.style.display = 'none';
        }, 5000);
    </script>
</body>

Stop Timer

 

 <button>Click Stop Timer</button>
    <script>
        var btn = document.querySelector('button');
        // Turn on the timer
        var timer = setTimeout(function() {
            console.log('Exploded');
        }, 5000);
        // Register click events for buttons
        btn.addEventListener('click', function() {
            // Stop Timer
            clearTimeout(timer);
        })
    </script>

setInterval() alarm timer

Turn on the timer

   <script>
        // 1. setInterval 
        setInterval(function() {
            console.log('Continue Output');
        }, 1000);
    </script>
 

Case: Countdown

 

 

    
<div>
        <span class="hour">1</span>
        <span class="minute">2</span>
        <span class="second">3</span>
    </div>
    <script>
        // 1. Get Elements (Time and Seconds box) 
        var hour = document.querySelector('.hour'); // Black box for hours
        var minute = document.querySelector('.minute'); // Black box for minutes
        var second = document.querySelector('.second'); // Black box for seconds
        var inputTime = +new Date('2019-5-1 18:00:00'); // Returns the total number of milliseconds of user input time
​
        countDown(); // Let's call this function once to prevent the first page refresh from getting blank 
​
        // 2. Turn on the timer
        setInterval(countDown, 1000);
        
        function countDown() {
            var nowTime = +new Date(); // Returns the total number of milliseconds in the current time
            var times = (inputTime - nowTime) / 1000; // times is the total number of seconds remaining 
            var h = parseInt(times / 60 / 60 % 24); //time
            h = h < 10 ? '0' + h : h;
            hour.innerHTML = h; // Give the remaining hours to the hour black box
            var m = parseInt(times / 60 % 60); // branch
            m = m < 10 ? '0' + m : m;
            minute.innerHTML = m;
            var s = parseInt(times % 60); // Current seconds
            s = s < 10 ? '0' + s : s;
            second.innerHTML = s;
        }
    </script>

Stop Timer

 

Case study: Countdown of sending SMS

After clicking the button, it can not be clicked again within 60 seconds to prevent sending SMS repeatedly.

 

 

    
Phone number: <input type="number"> <button>Send out</button>
    <script>
        var btn = document.querySelector('button');
        // Global variable, defining the number of seconds remaining
        var time = 3; 
        // Register Click Events
        btn.addEventListener('click', function() {
            // Disable button
            btn.disabled = true;
            // Turn on the timer
            var timer = setInterval(function() {
                // Judging the remaining seconds
                if (time == 0) {
                    // Clear timer and restore button
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.innerHTML = 'Send out';
                } else {
                    btn.innerHTML = 'Remaining' + time + 'second';
                    time--;
                }
            }, 1000);
        });
    </script>

1.2.6. this points to the problem

The direction of this is indeterminate at the time the function is defined. It is only when the function is executed that the direction of this can be determined. In general, this is ultimately the object that called it.

At this stage, let's first look at a few this points

  1. This points to the global object window in a global scope or function (note that this points to the window in the timer)

  2. Who calls this in a method call to whom

  3. Instance of this pointing to constructor in constructor

    
<button>click</button>
    <script>
        // this points to the problem this usually ends up with the object that called it
        // 1. This points to the global object window in the global scope or in a normal function (note that this points to the window in the timer)
        console.log(this);
        function fn() {
            console.log(this);
        }
        window.fn();
        window.setTimeout(function() {
            console.log(this);
        }, 1000);
        // 2. Who calls this in a method call points to whom
        var o = {
            sayHi: function() {
                console.log(this); // this is pointing to the o object
            }
        }
        o.sayHi();
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
                console.log(this); // this in the event handler points to the btn button object
            })
        // 3. Examples of this pointing to constructors in constructors
        function Fun() {
            console.log(this); // this points to a fun instance object
        }
        var fun = new Fun();
    </script>

1.2.7. location object

What is a location object

 

URL

 

 

Properties of the location object

 

 

Case study: 5 minutes automatic page Jump

 

 

    
<button>click</button>
    <div></div>
    <script>
        var btn = document.querySelector('button');
        var div = document.querySelector('div');
        btn.addEventListener('click', function() {
            // console.log(location.href);
            location.href = 'http://www.itcast.cn';
        })
        var timer = 5;
        setInterval(function() {
            if (timer == 0) {
                location.href = 'http://www.itcast.cn';
            } else {
                div.innerHTML = 'You will be' + timer + 'Jump to the first page in seconds';
                timer--;
            }
        }, 1000);
    </script>

Case: Getting URL parameters

 

 

    
<div></div>
    <script>
        console.log(location.search); // ?uname=andy
        // 1. Remove first? substr('start position', intercept several characters);
        var params = location.search.substr(1); // uname=andy
        console.log(params);
        // 2. Use = to split the string into arrays ('=');
        var arr = params.split('=');
        console.log(arr); // ["uname", "ANDY"]
        var div = document.querySelector('div');
        // 3. Write the data into the div
        div.innerHTML = arr[1] + 'Welcome';
    </script>

Common methods for location objects

 <button>click</button>
    <script>
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            // Record your browsing history so you can go back
            // location.assign('http://www.itcast.cn');
            // Browsing history is not recorded, so fallback is not possible
            // location.replace('http://www.itcast.cn');
            location.reload(true);
        })
    </script>

1.2.8. navigator object

The navigator object contains information about the browser and has many properties, most commonly the userAgent, which returns the value of the user-agent header of the sending server from the client.

The following front-end code can tell which user's terminal opens the page and makes a jump

if((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
    window.location.href = "";     //Mobile phone
 } else {
    window.location.href = "";     //Computer
 }

1.2.9 history object

The window object provides us with a history object to interact with the browser history. This object contains URL s that the user (in the browser window) has visited.

 

Hisry objects are rarely used in actual development, but they can be seen in some OA office systems.

 

1.3. JS Execution Mechanism

What is the result of executing the following code?

 console.log(1);
 
 setTimeout(function () {
     console.log(3);
 }, 1000);
 
 console.log(2);

What is the result of executing the following code?

 console.log(1);
 
 setTimeout(function () {
     console.log(3);
 }, 0);
 
 console.log(2);

1.3.1 JS is single threaded

 

    A single thread means that all tasks need to be queued before the last one can be executed. If the previous task takes a long time, the latter will have to wait.
    The problem with this is that if the JS takes too long to execute, the rendering of the page will be inconsistent, causing the rendering of the page to feel blocked by loading.

1.3.2 Synchronous and asynchronous tasks

The problem with single threading is that later tasks wait for the previous tasks to complete. If the previous tasks are time consuming (such as reading network data), later tasks have to wait all the time!!

To solve this problem, using the computing power of multi-core CPU s, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but the sub-threads are completely controlled by the main thread. Thus, synchronous and asynchronous tasks appear in JS.

synchronization

The execution order of the program is consistent with the order of tasks. For example, the synchronization of cooking: we want to boil and cook rice, wait for the water to boil (after 10 minutes), then cut and stir-fry vegetables.

asynchronous

When you do one thing, because it takes a long time, you can do other things at the same time. For example, in the asynchronous way of cooking, we use the 10 minutes to cut and stir-fry vegetables while boiling water.

 

All tasks in JS can be divided into two types, synchronous and asynchronous.
​
Synchronization tasks refer to:
    Tasks queued on the main thread can only be executed after the previous task has been executed.
Asynchronous tasks refer to:
    Tasks that do not enter the main thread but enter the Task Queue will not remove asynchronous tasks from the Task Queue until the tasks in the main thread are finished and put them into the main thread for execution.

 

1.3.3 JS Execution Mechanism (Event Loop)

 

 

 

1.3.4 Code Think Question

console.log(1);
 document.onclick = function() {
   console.log('click');
 }
​
 setTimeout(function() {
   console.log(3)
 }, 3000)
 console.log(2);

Tags: Javascript Front-end

Posted on Sat, 27 Nov 2021 12:14:49 -0500 by digitalmustache