[front end] front end advanced notes Part One

The best JS code is no JS code

Advanced notes of front end engineer Pary One

Part One

WEB development in progress

  • HTML is responsible for web page structure
  • CSS is responsible for the style of web page elements
  • JS is responsible for the interaction between web pages and users

To become an excellent front-end engineer, we need to abide by the principle that each of the three performs its own duties, so that the code is easy to maintain and expand.

Switching state

There is a task, and its specific requirements are as follows: a web page is switched between dark and light themes, so that readers who visit the web page at night can use the "night mode".

The HTML of this web page is like this:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTTP And HTTPS</title>
    <style>
        body,
        html {
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
            overflow: hidden;
        }
        
        body {
            padding: 10px;
            box-sizing: border-box;
        }
        
        div.pic img {
            width: 100%;
        }
        
        #modeBtn {
            font-size: 2rem;
            float: right;
        }
    </style>
</head>

<body>
    <div>
        <header>
            <button id="modeBtn">🌞</button>
            <h1>HTTP and HTTPS</h1>
        </header>
        <main>
            <div class="description">
                <p>
                    http: It is a standard for client-side and server-side requests and responses( TCP),Used from WWW Hypertext transfer protocol for the server to transfer hypertext to the local browser. https:The goal is safety HTTP Channel, i.e HTTP Add next SSL Layer for encryption. Its function is to establish an information security channel to ensure the transmission of data and the authenticity of the website
                </p>
            </div>
        </main>
    </div>
</body>

</html>

Generally speaking, our intuitive idea is to replace the background color of HTML and button icons by clicking events.

const btn = document.getElementById('modeBtn');
btn.addEventListener('click', (e) => {
  const body = document.body;
  if(e.target.innerHTML === '🌞') {
    body.style.backgroundColor = 'black';
    body.style.color = 'white';
    e.target.innerHTML = '🌜';
  } else {
    body.style.backgroundColor = 'white';
    body.style.color = 'black';
    e.target.innerHTML = '🌞';
  }
});

This code registers the click event for the button. When the user clicks the button, if the current button text is 🌞, The description is to change from day mode to night mode, change the background color of the body to dark color and the text style to light color.

But the above code has several problems:

  1. For others who don't understand the requirements, can you directly understand the meaning of pressing this button after reading this code?
  2. If the product requirements change, if it is required to display the night mode with other color background, can the JS code be avoided from modification?
  3. If you want to add animation effects to the switching process, is it convenient to add them?

Use class to represent the business state of the element

In story 1, elements are operated through JS code. The disadvantage is obvious: it is difficult for other code readers to understand the business requirements or states represented by styles through the code.

The main reason for this is that we entrusted the task that should have been completed by CSS to JS. CSS should have set the style of elements, but JS replaced it. Therefore, the code needs to be reconstructed to reflect its business needs.

  1. Return the element style in night mode to CSS;
  2. Refactoring JS code.

CSS:

body.night {
            background-color: black;
            color: white;
        }

JS:

const btn = document.getElementById('modeBtn');
btn.addEventListener('click', (e) => {
  const body = document.body;
  if(body.className !== 'night') {
    body.className = 'night';
    e.target.innerHTML = '🌜';
  } else {
    body.className = '';
    e.target.innerHTML = '🌞';
  }
});

The above code switches the day mode and night mode by clicking the event to switch the element state. Although the code change is very small, it only replaces the previous two lines of code with one line:

body.style.backgroundColor = 'black';
body.style.color = 'white';

=>

body.className = 'night';

But it solves the three problems we mentioned earlier:

  1. First, set classname to night. This operation itself can reveal some demand information, which is convenient for maintainers to quickly understand business requirements.
  2. Secondly, if the product requirements change and the switched color needs to be replaced, there is no need to change the JS code, just the body Night style is enough!
  3. Finally, to add animation effect to the switching process, you can use the transition animation supported by CSS3, such as:
body {
  padding: 10px;
  box-sizing: border-box;
  transition: all 1s;
}
body.night {
  background-color: black;
  color: white;
  transition: all 1s;
}

Finally, you can add e.target. As an element innerHTML = ' 🌜'; Switch to CSS as follows:

#modeBtn::after {
  content: '🌞';
}
body.night #modeBtn::after {
  content: '🌜';
}

Remove the text content in the middle of < button id ='modebtn '> < / button > in HTML and simplify the JS code into:

const btn = document.getElementById('modeBtn');
btn.addEventListener('click', (e) => {
  const body = document.body;
  if(body.className !== 'night') {
    body.className = 'night';
  } else {
    body.className = '';
  }
});

The class attribute of the element is not only to provide the element selector for CSS. So far, we have realized that JS is only responsible for switching the element state, and returning the change of element style to CSS, which ensures the principle of performing their respective duties. Our code can not only reflect the needs of the business, but also conducive to the maintenance and expansion in the future.

The best JS code is no JS code

So is there a way that we only use CSS to achieve the "night mode" effect? For the need to switch the night mode, the core problem is to use CSS instead of JS to switch and remember the state of interaction with users.

In HTML, the element that can complete the state switching can be thought of as the checkbox in the form at the first time. Modify the HTML:

<input id="modeCheckBtn" type="checkbox">
    <div class="content">
        <header>
            <label id="modeBtn" for="modeCheckBtn"></label>
            <h1>HTTP and HTTPS</h1>
        </header>
        <main>
            <div class="description">
                <p>
                    http: It is a standard for client-side and server-side requests and responses( TCP),Used from WWW Hypertext transfer protocol for the server to transfer hypertext to the local browser. https:The goal is safety HTTP Channel, i.e HTTP Add next SSL Layer for encryption. Its function is to establish an information security channel to ensure the transmission of data and the authenticity of the website
                </p>
            </div>
        </main>
    </div>

We added an input element with type = "checkbox" in the above code, and the selected state of the element can be marked through the pseudo class selector.

Since the < input > element is the first child element of the body, the child elements behind it can be selected through the sibling node selector of CSS.

Adjust the style of the previous version and move the style of body to In the content container, put the body The style of night moves to #modecheckbtn: checked + Content rule.

        body {
            box-sizing: border-box;
        }
        
        .content {
            padding: 10px;
            transition: all 1s;
        }
        
        #modeBtn {
            font-size: 2rem;
            float: right;
        }
        
        #modeCheckBtn:checked+.content {
            background-color: black;
            color: white;
        }
        
        #modeBtn::after {
            content: '🌞';
        }
        
        #modeCheckBtn:checked+.content #modeBtn::after {
            content: '🌜';
        }
        
        #modeCheckBtn {
            display: none;
        }

In this way, you can click the checkbox to switch the "night mode", but it is impossible for the user to switch by clicking the selection box. Therefore, we can use the label element instead of the checkbox to trigger the user's click behavior.

The id specified by the for attribute of the label element can bind the label element to the corresponding form element.

        <header>
            <label id="modeBtn" for="modeCheckBtn"></label>
            <h1>HTTP and HTTPS</h1>
        </header>

Then hide the checkbox:

        #modeCheckBtn {
            display: none;
        }

The complete code is as follows:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Late night canteen</title>
    <style>
        body,
        html {
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
            overflow: hidden;
        }
        
        body {
            box-sizing: border-box;
        }
        
        body.night {
            background-color: black;
            color: white;
            transition: all 1s;
        }
        
        .content {
            padding: 10px;
            transition: all 1s;
        }
        
        #modeBtn {
            font-size: 2rem;
            float: right;
        }
        
        #modeCheckBtn:checked+.content {
            background-color: black;
            color: white;
        }
        
        #modeBtn::after {
            content: '🌞';
        }
        
        #modeCheckBtn:checked+.content #modeBtn::after {
            content: '🌜';
        }
        
        #modeCheckBtn {
            display: none;
        }
    </style>
</head>

<body>
    <input id="modeCheckBtn" type="checkbox">
    <div class="content">
        <header>
            <label id="modeBtn" for="modeCheckBtn"></label>
            <h1>HTTP and HTTPS</h1>
        </header>
        <main>
            <div class="description">
                <p>
                    http: It is a standard for client-side and server-side requests and responses( TCP),Used from WWW Hypertext transfer protocol for the server to transfer hypertext to the local browser. https:The goal is safety HTTP Channel, i.e HTTP Add next SSL Layer for encryption. Its function is to establish an information security channel to ensure the transmission of data and the authenticity of the website
                </p>
            </div>
        </main>
    </div>
</body>

</html>

No matter how simple the code is, there may be bugs. The only way to avoid bugs is not to use the code. Therefore, the best JS code is no JS code.

Tags: html Javascript css

Posted by mrjap1 on Tue, 19 Apr 2022 10:48:40 +0930