Lesson 03-Basic Use of New HTML5 Tags and DOM Operations

Introduction to HTML5

Timeline of Web Technology Development

  • 1991 HTML
  • 1994 HTML2
  • 1996 CSS1 + JavaScript
  • 1997 HTML4
  • 1998 CSS2
  • 2000 XHTML1 (strict HTML)
  • 2002 Tableless Web Design (table layout)
  • 2005 AJAX
  • 2009 HTML5
  • 2014 HTML5 Finalized

The table layout in 2002 was gradually eliminated because: the table is used to carry data, not to divide the structure of the web page.

The draft of HTML5 was launched in 2009, but it was not finalized until 2014 because of the promotion of mobile terminals.

The predecessor of the H5 draft was called: Web Application, which was first proposed by the WHATWG organization in 2004.

It was accepted by the W3C organization in 2007 and the first draft of HTML5 was released on 2008-01-22.

What is HTML5

HTML5 is not just the latest version of the HTML markup language, but more importantly, it establishes a series of standards for Web application development, becoming the first HTML language to use the Web as an application development platform.

HTML5 defines a series of new elements, such as new semantic tags, smart forms, multimedia tags, etc., which can help developers create rich Internet applications. It also provides some Javascript APIs, such as geolocation, gravity sensing, hardware access, etc., which can realize native-like applications in the browser. We can even develop web games in combination with Canvas.

The broad concept of HTML5: HTML5 represents a development stage of browser-side technology. At this stage, browser presentation technology has made great progress and has gained wide support. It includes a set of technologies including HTML5, CSS3, and Javascript API.

HTML5 is not equal to HTML next version. HTML5 includes: an upgraded version of HTML, an upgraded version of CSS, and an upgraded version of JavaScript API.

Summary: HTML5 is a new generation of Web rich client application overall solution. It includes: a technical combination including HTML5, CSS3, and Javascript API.

Rich client: A client program with strong interactivity and experience. For example, browsing a blog is a relatively simple client; a website for listening to music online or an instant messaging website is a rich client.

PS:

From a purely technical perspective, compatibility issues will only cause unnecessary troubles for developers.

If the web-side program can achieve the experience of a PC client, it will pose a threat to the latter.

Application scenarios of HTML5

List several application scenarios of HTML5:

(1) Highly expressive web pages: The content is simple but not simplistic.
(2) Web applications:

  • Software that replaces PC: iCloud, Baidu Mind Map, Office 365, etc.
  • Web pages on the APP side: Taobao, JD.com, Meituan, etc.
  • WeChat side: public accounts, mini programs, etc.
    (3) Hybrid local applications.
    (4) Simple games.

New content in HTML5

TagsAttributesSmart formsWeb multimediaCanvasSVG
Semantic tagsLink relationship descriptionNew form typesAudio2D
Application tagsStructured data tagsVirtual keyboard adaptationVideo3D (WebGL)
ARIASubtitles
Custom attributes

Detailed explanation of new content in HTML5

Semantic tags

The role of semantics

Semantic tags are not unfamiliar to us, such as <p> represents a paragraph, and <ul> represents an unordered list. The role of semantic tags:

  • It makes it easier for developers to read and write more elegant code.
  • At the same time, it allows browsers or web crawlers to parse well, so as to better analyze the content.
  • Better SEO.

Summary: HTML’s job is to describe what a piece of content is (or its meaning), not what it looks like; its appearance should be determined by CSS.

H5’s semantic improvements

On this basis, HTML5 adds a large number of meaningful semantic tags, which is more conducive to search engines or auxiliary devices to understand the content of HTML pages. HTML5 will make the content of HTML code more structured and the tags more semantic.

Traditional web page layout:

<!-- Header -->
<div class="header">
    <ul class="nav"></ul>
</div>

<!-- Main body -->
<div class="main">
    <!-- Article -->
    <div class="article"></div>
    <!-- Sidebar -->
    <div class="aside"></div>
</div>

<!-- Bottom -->
<div class="footer">

</div>

H5 classic web page layout:

<!-- Header -->
<header>
    <ul class="nav"></ul>
</header>

<!-- Main body -->
<div class="main">
    <!-- Article -->
    <article></article>
    <!-- Sidebar -->
    <aside></aside>
</div>

<!-- Bottom -->
<footer>

</footer>

New semantic tags in H5

  • <section> indicates a section
  • <article> indicates an article. Such as articles, comments, posts, blogs
  • <header> indicates a header
  • <footer> indicates a footer
  • <nav> indicates navigation
  • <aside> indicates a sidebar. Such as the sidebar of an article
  • <figure> indicates a media content grouping
  • <mark> indicates a mark (rarely used)
  • <progress> indicates progress (rarely used)
  • <time> indicates a date

Essentially, the new semantic tag is no different from <div> and <span>, except that it is expressive. When using it, except for the need to pay attention to the HTML structure, there is no difference from the use of ordinary tags. It can be understood that <div class="nav"> is equivalent to <nav>.

PS: Single tags do not need to write a closing symbol.

Compatibility processing of new semantic tags

IE8 and below do not support H5 and CSS3. Solution: import the html5shiv.js file.

When importing, you need to make an if judgment, the specific code is as follows:

<!-- Conditional comments can only be recognized by IE-->

<!--[if lte ie 8]>
<script src="html5shiv.min.js"></script>
<![endif]-->

The above code is conditional comment: Although it is a comment, IE browser can recognize it. Explanation:

  • l: less smaller
  • t: than
  • e: equal equal
  • g: great greater

PS: When we test the compatibility of IE browser, we can use the software ietest to simulate IE6-IE11.

In browsers that do not support HTML5 new tags, these new tags will be parsed as inline elements, so we only need to convert them into block elements to use.

However, in versions below IE9, these new tags cannot be parsed normally, but custom tags created by document.createElement(‘tagName’) can be recognized. So our solution is to create all HTML5 new tags through document.createElement(‘tagName’), so that lower versions of IE can also parse HTML5 new tags normally.

Of course, in actual development, we more often use the method of detecting the version of IE browser to load third-party JS libraries to solve compatibility issues (as shown in the code above).

Forms in H5

Traditional Web forms are increasingly unable to meet development needs. HTML5 has made great improvements in the direction of Web forms, such as color pickers, date/time components, etc., making form processing more efficient.

New form types in H5

  • email can only enter email format. Automatically with verification function.
  • tel mobile phone number.
  • url can only input the URL format.
  • number can only input numbers.
  • search search box
  • range slider
  • color color picker
  • time time
  • date date
  • datetime time and date
  • month month
  • week week

Some of the above types are effective for mobile devices and have certain compatibility. They can be used selectively in actual applications.

Code example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Form Type</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #F7F7F7;
        }

        form {
            max-width: 500px;
            width: 100%;
            margin: 32px auto 0;
            font-size: 16px;
        }

        label {
            display: block;
            margin: 10px 0;
        }

        input {
            width: 100%;
            height: 25px;
            margin-top: 2px;
            display: block;
        }

    </style>
</head>
<body>
<form action="">
    <fieldset>
        <legend>Form Type</legend>
        <label for="">
            email: <input type="email" name="email" required>
        </label>
        <label for="">
            color: <input type="color" name="color">
        </label>
        <label for="">
            url: <input type="url" name='url'>
        </label>
        <label for="">
            number: <input type="number" step="3" name="number">
        </label>
        <label for="">
            range: <input type="range" name="range" value="100">
        </label>
        <label for="">
            search: <input type="search" name="search">
        </label>
        <label for="">
            tel: <input type="tel" name="tel">
        </label>
        <label for="">
            time: <input type="time" name="time">
        </label>
        <label for="">
            date: <input type="date" name="date">
        </label>
        <label for="">
            datetime: <input type="datetime">
        </label>
        <label for="">
            week: <input type="week" name="month">
        </label>
        <label for="">
            month: <input type="month" name="month">
        </label>
        <label for="">
            datetime-local: <input type="datetime-local" name="datetime-local">
        </label>
        <input type="submit">
    </fieldset>
</form>
</body>
</html>

Code explanation:

The <fieldset> tag packages the content in the form and represents a group; while the <legend> tag defines the title of the element in the fieldset.

Form elements (labels)

Here are two form elements.

1. <datalist> Data list:

<input type="text" list="myData">
<datalist id="myData">
    <option>Undergraduate</option>
    <option>Graduate</option>
    <option>Unknown</option>
</datalist>

In the above code, the list attribute in the input is bound to the datalist, and the data list can be automatically prompted.

  1. <keygen> element:

The function of the keygen element is to provide a reliable method to verify users.

The keygen element is a key-pair generator. When the form is submitted, two keys are generated: a public key and a private key.

The private key is stored on the client, and the public key is sent to the server. The public key can be used to later verify the user’s client certificate.

  1. <meter> element: meter
  • low: warn if it is lower than this value
  • high: warn if it is higher than this value
  • value: current value
  • max: maximum value
  • min: minimum value.

Example:

<meter value="81" min="0" max="100" low="60" high="80"/>

Form attributes

  • placeholder placeholder (prompt text)
  • autofocus automatic focus
  • multiple file upload multiple selections or multiple email addresses
  • autocomplete automatic completion (filled). on (default), off (cancel). Used for form elements, and also for the form itself (on/off)
  • form specifies which form the form item belongs to, which is needed when processing complex forms
  • novalidate turns off the default validation function (can only be added to form)
  • required indicates a required field
  • pattern customizes the regular expression to validate the form. For example

Code example:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        form {
            width: 100%;
            /* Maximum Width*/
            max-width: 640px;
            /* Minimum Width*/
            min-width: 320px;
            margin: 0 auto;
            font-family: "Microsoft Yahei";
            font-size: 20px;
        }

        input {
            display: block;
            width: 100%;
            height: 30px;
            margin: 10px 0;
        }
    </style>
</head>
<body>

<form action="">
    <fieldset>
        <legend>Form properties</legend>
        <label for="">
            username:<input type="text" placeholder="For example: smyhvae" autofocus name="userName" autocomplete="on" required/>
        </label>

        <label for="">
            tel:<input type="tel" pattern="1\d{10}"/>
        </label>

        <label for="">
            multiple的表单: <input type="file" multiple>
        </label>

        <!-- Upload files-->
        <input type="file" name="file" multiple/>

        <input type="submit"/>
    </fieldset>
</form>

</body>
</html>

Form events

  • oninput(): Triggered when the user enters content, can be used to count the number of words entered.
  • oninvalid(): Triggered when the validation fails. For example, if you want to pop up a prompt text when the validation fails, you can use it.

Example:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        form {
            width: 100%;
            /* Maximum width*/
            max-width: 400px;
            /* Minimum width*/
            min-width: 200px;
            margin: 0 auto;
            font-family: "Microsoft Yahei";
            font-size: 20px;
        }

        input {
            display: block;
            width: 100%;
            height: 30px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
<form action="">
    <fieldset>
       <legend>Form event</legend>
        <label for="">
        Email: <input type="email" name="" id="txt1"/>
        </label>
        <label for="">
        Number of inputs: <input type="text" name="" id="txt2"/>
        </label>

        <input type="submit"/>
    </fieldset>
</form>
<script>

    var txt1 = document.getElementById('txt1');
    var txt2 = document.getElementById('txt2');
    var num = 0;

    txt1.oninput = function () { //Triggered when the user inputs

        num++; //Num automatically increases by 1 each time the user inputs
        //Display the statistics in txt2
        txt2.value = num;
    }
    txt1.oninvalid = function () { //Triggered when the verification fails
        this.setCustomValidity('Dear, please enter correctly'); //Set the prompt text when the verification fails
    }

</script>
</body>
</html>

Multimedia Applications

Before HTML5, the common method of playing audio/video on a web page was to use Flash. However, in most cases, not all users have Flash plug-ins installed on their browsers, which makes the processing of audio and video playback very complicated; and the browsers of mobile devices do not support Flash plug-ins.

H5 provides tags for video and audio.

Audio

HTML5 solves the problem of audio playback through the <audio> tag.

Example of use:

<audio src="music/yinyue.mp3" autoplay controls> </audio>

We can use additional attributes to control audio playback more friendly, such as:

  • autoplay automatic playback. Write autoplay or autoplay = "", both are OK.
  • controls control bar. (It is recommended to write this option, otherwise you can’t see where the controls are)
  • loop loop playback.
  • preload preload When autoplay is set at the same time, this attribute will be invalid.
    In order to achieve multi-browser support, the following compatibility writing method can be adopted:
<!--Recommended compatible writing method:-->
<audio controls loop>
<source src="music/yinyue.mp3"/>
<source src="music/yinyue.ogg"/>
<source src="music/yinyue.wav"/>
Sorry, your browser does not support this audio format
</audio>

Code explanation: If the audio format cannot be recognized, the “sorry” message will pop up.

Video

HTML5 uses the <video> tag to solve the problem of video playback.

Example of use:

<video src="video/movie.mp4" controls autoplay></video>

We can use additional attributes to control the playback of videos more friendly, such as:

  • autoplay automatic playback. Written as autoplay or autoplay = "", both are OK.
  • controls control bar. (It is recommended to write this option, otherwise you can’t see where the control is)
  • loop loop playback.
  • preload preload When autoplay is set at the same time, this property will be invalid.
  • width: Set the playback window width.
  • height: Set the height of the playback window.
<!--<video src="video/movie.mp4" controls autoplay ></video>-->
<!-- Inline block display:inline-block -->
<video controls autoplay>
<source src="video/movie.mp4"/>
<source src="video/movie.ogg"/>
<source src="video/movie.webm"/>
Sorry, this video is not supported
</video>

Simple player example

<!-- Multimedia-->
<figure>
    <!-- Multimedia title-->
    <figcaption>Video case</figcaption>
    <div class="palyer">
        <video src="video/fun.mp4"></video>
        <!-- Control bar-->
        <div class="controls">
        <!-- Play and pause-->
            <a href="#" class="switch icon-play"></a>
            <div class="progress">
                <!-- Current progress-->
                <div class="curr-progress"></div>
            </div>
            <!-- Time-->
            <div class="time">
                <span class="curr-time">00:00:00</span>/<span class="total-time">00:00:00</span>
            </div>
            <!-- Full screen-->
            <a href="#" class="extend icon-resize-full"></a>
        </div> 
    </div> 
</figure>
// Idea:
/*
* 1. Click the button to pause the playback and switch the icon
* 2. Calculate the total time of the video and display it
* 3. When the video is playing, the progress bar is synchronized with the current time
* 4. Click to achieve full screen
*/

// Get the required tags
var  video=document.querySelector('video');
// Play button
var playBtn=document.querySelector('.switch');
// Current progress bar
var currProgress=document.querySelector('.curr-progress');
// Current time
var currTime=document.querySelector('.curr-time');
// Total time
var totalTime=document.querySelector('.total-time');
// Full screen
var extend=document.querySelector('.extend');

var tTime=0;

// 1. Click the button to pause and switch icons

playBtn.onclick=function(){
//               If the video is playing, pause it; if it is paused, play it
   if(video.paused){
//                   play
       video.play();
       //Toggle Icon
       this.classList.remove('icon-play');
       this.classList.add('icon-pause');
   }else{
//                   pause
        video.pause();
//                   Toggle Icon
       this.classList.remove('icon-pause');
       this.classList.add('icon-play');}
}

// 2. Calculate the total time of the video and display it
// When the loading is complete, the video can be played
video.oncanplay=function(){
//             Get the total duration of the video
    tTime=video.duration;
    console.log(tTime);

//          Convert the total seconds into hours, minutes, and seconds format: 00:00:00
//          Hours
    var h=Math.floor(tTime/3600);
//            minute
    var m=Math.floor(tTime%3600/60);
//            Second
    var s=Math.floor(tTime%60);

//            console.log(h);
//            console.log(m);
//            console.log(s);

//            Convert the data format to 00:00:00
    h=h>=10?h:"0"+h;
    m=m>=10?m:"0"+m;
    s=s>=10?s:"0"+s;


    console.log(h);
    console.log(m);
    console.log(s);
//            Show it up
    totalTime.innerHTML=h+":"+m+":"+s;
}
// *    3. When the video is playing, the progress bar is synchronized with the current time
//      Triggered when the current time is updated
video.ontimeupdate=function(){
// Get the current playing time of the video
// console.log(video.currentTime);
// Current playing time
var cTime=video.currentTime;
// Convert the format to 00:00:00

var h=Math.floor(cTime/3600);
// Minutes
var m=Math.floor(cTime%3600/60);
// Seconds
var s=Math.floor(cTime%60);

// Convert the data format to 00:00:00
h=h>=10?h:"0"+h;
m=m>=10?m:"0"+m;
s=s>=10?s:"0"+s;

// Display the current time
currTime.innerHTML=h+":"+m+":"+s;

// Change the width of the progress bar: current time/total time
    var value=cTime/tTime;

    currProgress.style.width=value*100+"%";

}

//        full screen
extend.onclick=function(){
//            Full screen h5 code
    video.webkitRequestFullScreen();
}

HTML5 DOM operation

DOM operation

Get element

  • document.querySelector(“selector”) Get the first element that meets the conditions through the CSS selector.
  • document.querySelectorAll(“selector”) Get all elements that meet the conditions through the CSS selector, in the form of a class array.

Class name operation

  • Node.classList.add(“class”) Add class
  • Node.classList.remove(“class”) Remove class
  • Node.classList.toggle(“class”) Switch class, remove if there is, add if there is not
  • Node.classList.contains(“class”) Check whether there is a class

Custom attributes

In js, you can customize and get attributes through box1.index=100; box1.title.

H5 can add custom attributes directly in the tag, but it must start with data-.

Example:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<!-- Add custom attributes to tags. Must start with data- -->
<div class="box" title="box" data-my-name="smyhvae" data-content="I am a div">div</div>
<script>
    var box = document.querySelector('.box');
    //Custom attributes need to be obtained through dateset[]
    console.log(box.dataset["content"]); //Print result: I am a div
    console.log(box.dataset["myName"]); //Print result: smyhvae
    //Set the value of the custom attribute
    var num = 100;
    num.index = 10;
    box.index = 100;
    box.dataset["content"] = "aaaa";
</script>
</body>
</html>

Example: When the mouse is clicked, the tab bar switches

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

<head>
    <meta charset="UTF-8">
    <title>Tab tag</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #F7F7F7;
        }

        .tabs {
            width: 400px;
            margin: 30px auto;
            background-color: #FFF;
            border: 1px solid #C0DCC0;
            box-sizing: border-box;
        }

        .tabs nav {
            height: 40px;
            text-align: center;
            line-height: 40px;
            overflow: hidden;
            background-color: #C0DCC0;
            display: flex;
        }

        nav a {
            display: block;
            width: 100px;
            border-right: 1px solid #FFF;
            color: #000;
            text-decoration: none;
        }

        nav a:last-child {
            border-right: 0 none;
        }

        nav a.active {
            background-color: #9BAF9B;
        }

        .cont {
            overflow: hidden;
            display: none;
        }

        .cont ol {
            line-height: 30px;
        }
    </style>
</head>

<body>
    <div class="tabs">
        <nav>
            <a href="javascript:;" data-cont="local">Domestic News</a>
            <a href="javascript:;" data-cont="global">Domestic News</a>
            <a href="javascript:;" data-cont="sports">Sports News</a>
            <a href="javascript:;" data-cont="funny">Sports News</a>
        </nav>
        <section class="cont" id="local">
            <ol>
                <li>Sports News</li>
                <li>Sports News</li>
                <li>Sports News</li>
                <li>Sports News</li>
            </ol>
        </section>
        <section class="cont" id="global">
            <ol>
                <li>Sports News</li>
                <li>Sports News</li>
                <li>Sports News</li>
                <li>Sports News</li>
            </ol>
        </section>
        <section class="cont" id="sports">
            <ol>
                <li>Sports News</li>
                <li>Sports News</li>
                <li>Sports News</li>
                <li>Sports News</li>
            </ol>
        </section>
        <section class="cont" id="funny">
            <ol>
                <li>Sports News</li>
                <li>Sports News</li>
                <li>Sports News</li>
                <li>Sports News</li>
            </ol>
        </section>
    </div>
    <script>
       // Target: Display a current style by default
        // Click navigation to switch
        // key indicates the number of items currently displayed

       (function (key) {
            // Get all navigations
            var navs = document.querySelectorAll('nav a');
            // Traverse, bind events to navigations, and add current styles
            for (var i = 0; i < navs.length; i++) {
            // If it is the current style specified by the user
                if (key == i) {
                    navs[i].classList.add('active');
                    // Get the id of the section to display content
                    var secId = navs[i].dataset['cont'];
                    // Get the corresponding section tag
                    document.querySelector('#' + secId).style.display = 'block';
                }

                // Bind click events to each navigation
                navs[i].onclick = function () {
                // Exclusive
                // Clear the previously active style, hide the previously displayed section
                var currentNav = document.querySelector('.active');
                // Get the corresponding content area , make it hidden
                var currentId = currentNav.dataset['cont'];
                // Remove the active style of the navigation
                currentNav.classList.remove('active');
                // Corresponding content area
                document.querySelector('#' + currentId).style.display = 'none';

                // Highlight yourself Navigation add style Corresponding section display
                // Add active style to yourself
                this.classList.add('active');
                // The corresponding section module is displayed
                var myId = this.dataset['cont'];
                document.querySelector('#' + myId).style.display = 'block';
            }
            }

        })(0);


    </script>
</body>

</html>
Share your love