YK bacteria has learned a lot of languages since college (C/ Java/Matlab/Pathon /), and finally confirmed that JavaScript is my native language. At the beginning, I thought it was really quick and easy to learn JavaScript, but with the further learning, It’s really fun to find JavaScript, prototypes, closures, and so on. I love JavaScript ~

Participated in the byte youth training camp activities, saw the legendary moon shadow teacher, the key also listened to him give us two how to write good JS class! It’s so profitable. Today, I will share what I have learned in class and study with you! ~

Yue Ying teaches us three principles for writing good JavaScript (including other languages) : ① Responsibility for each component; ② component encapsulation; and ③ process abstraction

Of course, there are more than these three principles, but these three principles are relatively important. Therefore, the three principles I mentioned directly should actually be called several principles

Today we are going to look at the first principle — each to his own responsibility

1. Start

Last time I talked about the “troika” of the front end in HTML Basics, one of them is JavaScript, which is responsible for the behavior of the page

Let’s make JavaScript responsible for the behavior of the page. Here’s an example

2. Dark mode

Now many web pages support light mode and dark mode switch, so how to use JavaScript to achieve?

New ShouBan

First, let’s look at the structure of the page, HTML

  <header>
    <button id="modeBtn">🌞</button>
    <h1>YK bacterium's blog is very good</h1>
  </header>

  <main>
    <div class="pic">
      <img src="https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/154b55eb36c8ae10f701e2d3d6cfb138~300x300.image">
    </div>
    <div class="description">
      <p>This is the blog of YK bacteria, I used to write blog in C station, then I participated in the youth camp activities, transferred to the nuggets, the community is very good ~ many activities ~ often come to nuggets ~~<hr />The previous blog and now are the same, are some notes and so on, I am a new front, first to take notes ~~ take good notes, slowly expand ~<hr />
        <strong>YK bacteria</strong>, ah ~ ~ ~ ~</p>
    </div>
  </main>
Copy the code

Then let’s look at our page’s style CSS

    body.html {
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
      overflow: hidden;
    }

    body {
      padding: 10px;
      box-sizing: border-box;
    }

    #modeBtn {
      font-size: 2rem;
      float: right;
      border: none;
      background: transparent;
    }
Copy the code

Finally, let’s look at the behavior of our page JavaScript

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 = '🌞'; }});Copy the code

Let’s look at the logic of the JavaScript code above

  1. Gets the toggle button element
  2. Bind mouse click events to buttons
  3. Gets the page body element
  4. Determine whether the current button element is 🌞 or 🌜
  5. 🌞 changes the background color of the page to black, the font color to white, and the button element to 🌜
  6. Otherwise the button is 🌜, we change the page background color to white, the font to black, and the button element to 🌞

As a front-end newcomer, I think this code is not bad ~ logic is very clear, the function can also

But this code violates the principle that we all have our own responsibilities!

This JavaScript code modifies both the style and structure of the element!!

Let’s think about it this way: if this code were shown to someone without any context (HTML/CSS), what would they read? You can stop and think about it

In fact, only give you to read this section of JavaScript code, you know only this section of code will modify some style, modify some structure, but you do not know the meaning of this section of JavaScript is to complete the page dark and light mode switch such a function!

There are also some questions, if you want to change the font color in dark mode to another color, do you need to modify the JS code to operate? Is it easy to add some transition effects to black and white?

So the new version of the code, not good enough! You can optimize

Novice optimized edition

How do you optimize it? We can use CSS to add class styles to elements and let JavaScript change their class names. In this way, JavaScript does not have to manipulate style directly, which is the separation of style and behavior. Let’s try it out

Let’s take a look at the structure of the page

  <header>
    <button id="modeBtn"></button>
    <h1>YK bacterium's blog is very good</h1>
  </header>

  <main>
    <div class="pic">
      <img src="https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/154b55eb36c8ae10f701e2d3d6cfb138~300x300.image">
    </div>
    <div class="description">
      <p>This is the blog of YK bacteria, I used to write blog in C station, then I participated in the youth camp activities, transferred to the nuggets, the community is very good ~ many activities ~ often come to nuggets ~~<hr />The previous blog and now are the same, are some notes and so on, I am a new front, first to take notes ~~ take good notes, slowly expand ~<hr />
        <strong>YK bacteria</strong>, ah ~ ~ ~ ~</p>
    </div>
  </main>
Copy the code

The structure of the page is unchanged except for the deletion of 🌞 in the button

Let’s take a look at the page style CSS

    body.html {
      width: 100%;
      height: 100%;
      max-width: 600px;
      padding: 0;
      margin: 0;
      overflow: hidden;
    }

    body {
      padding: 10px;
      box-sizing: border-box;
      transition: all 1s;
    }

    #modeBtn {
      font-size: 2rem;
      float: right;
      border: none;
      outline: none;
      cursor: pointer;
      background: inherit;
    }

    body.night {
      background-color: black;
      color: white;
      transition: all 1s;
    }

    #modeBtn::after {
      content: '🌞';
    }

    body.night #modeBtn::after {
      content: '🌜';
    }
Copy the code
  1. Provide 🌞 and 🌜 content by adding after elements to the button, eliminating the need for JAVASCRIPT to modify the structure of the page
  2. By setting the night class name, make the background of the page black and the font color white to achieve the black mode, and add the transition effect
  3. This allows elements to display different styles by setting different class names

Finally, JavaScript is pretty easy to write

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

In this code, you can see that JavaScript just changes the element’s className, className, without directly manipulating the page style, and readability is greatly improved. (Because the class name can well reflect the needs of this business, try the Night Black mode)

And you can do a lot more things in your CSS, like you can add transitions here: all 1s; To make the user experience better! More extensible, if you want to change the requirements, such as to change the color of the font, just need to change the CSS code ~

Well done here, but is there a better solution?

The master version

A true master is someone who can win without using any skills.

Here’s the master version of the solution: don’t write JavaScript

The best JS code is not to write JS!! How to write JS without bugs is not to write JS!!

Page structure HTML

  <input id="modeCheckBox" type="checkbox">
  <div class="content">
    <header>
      <label id="modeBtn" for="modeCheckBox"></label>
      <h1>YK bacterium's blog is very good</h1>
    </header>

    <main>
      <div class="pic">
        <img src="https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/154b55eb36c8ae10f701e2d3d6cfb138~300x300.image">
      </div>
      <div class="description">
        <p>This is the blog of YK bacteria, I used to write blog in C station, then I participated in the youth camp activities, transferred to the nuggets, the community is very good ~ many activities ~ often come to nuggets ~~<hr />The previous blog and now are the same, are some notes and so on, I am a new front, first to take notes ~~ take good notes, slowly expand ~<hr />
          <strong>YK bacteria</strong>, ah ~ ~ ~ ~</p>
      </div>
    </main>
  </div>
Copy the code

The structure here is a little different. We first wrap the content we want to display in a large box, and then replace the button element with a label element that points to the checkbox element outside the big box

Now let’s look at what page style CSS is, okay

    body.html {
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
      overflow: hidden;
    }

    body {
      box-sizing: border-box;
    }

    .content {
      padding: 10px;
      transition: background-color 1s, color 1s;
    }

    #modeCheckBox {
      display: none;
    }

    #modeCheckBox:checked+.content {
      background-color: black;
      color: white;
      transition: all 1s;
    }

    #modeBtn {
      font-size: 2rem;
      float: right;
    }

    #modeBtn::after {
      content: '🌞';
    }

    #modeCheckBox:checked+.content #modeBtn::after {
      content: '🌜';
    }
Copy the code

Let’s take a look at the code here

  1. Because of the structure of HTML, clicking on label is equivalent to clicking on the checkbox. It can remember the user’s state by clicking on it. The checked and unchecked states correspond to white mode and dark mode.
  2. Hide the checkbox outside the larger boxdisplay: none;(There is a label pointing to the checkbox)
  3. Clicking checkBox triggers the pseudo class via checkBox’s pseudo class selector

The: Checked selector matches each selected input element (for radio buttons and check boxes only).

  1. Through the adjacent sibling selector+Select the big box below the checkbox

The adjacent sibling selector (+) is between two selectors, and the second element is selected when the second element follows the first and both elements are children of the same parent.

Developer.mozilla.org/zh-CN/docs/…

  1. This allows the CSS control element to switch styles when clicked

This is fantastic

So let’s display the checkbox, and let’s see

Pay attention to

The pure master version here may not be very compatible because it uses a sibling element selector, which is a good choice regardless of compatibility. Also, the master version adds a few tricks to the HTML to change the structure of some pages, which may require some experience

Best practices

  • HTML, CSS, and JavaScript do their part
  • Unnecessary direct manipulation of styles by JS should be avoided
  • You can useclassClass names have good business semantics
  • Pure presentation class interaction seeks zero JavaScript solutions

More related posts

[Youth Training camp] Teacher Yue Ying told me the three principles of writing good JavaScript — each is responsible for his own work

[Youth Training Camp] Teacher Yue Ying told me the three principles of good JavaScript writing — component encapsulation

[Youth Training Camp] Teacher Yue Ying told me the three principles of good JavaScript – process abstraction

[Youth Training Camp] Teacher Yue Ying told me four skills to write good JavaScript — style first

[Youth Training Camp] Teacher Yue Ying told me four skills to write good JavaScript — make sure it is correct