Front end case: my memo (supports the addition, deletion and modification of events, and the code is complete)

Posted by nickthegreek on Sat, 05 Mar 2022 21:50:03 +0100

This case does not use any framework. It is implemented using js native and DOM operation. The code is complete and can be copied and used immediately.

catalogue

1, Case effect

2, Key points involved

1. Event monitoring

2. DOM node operation

(1) Common node acquisition methods

(2) Common node information acquisition methods

(3) Common node attribute acquisition method

(4) DOM modification

(5) DOM add

(6) DOM deletion

3. DOM controls CSS Style

(1) Control the style through the style attribute

(2) Control style through classList:

3, Complete code + detailed comments

1, Case effect

As shown in the figure below, the memo can add new events, edit events, delete existing events, and mark completed events.

2, Key points involved

1. Event monitoring

The corresponding event can be triggered only after the event source is bound with the event. There are three ways of event binding: in-line event attribute assignment, event attribute assignment and event listening.

This case uses the event listening method for event binding. The difference between this case and the other two methods is that if the event attribute is assigned multiple times, only the last event handler will be executed; Event listener can add multiple listeners and execute multiple event handlers.

The event listening format is:

addEventListener(type, listener, useCapture)

//Type: event type
//Listener: listener (handler)
//useCapture: the default is false. When set to true, the listener will not be triggered due to bubbling

//eg: 
const btn = document.querySelector('button');
btn.addEventListener('click', function() {
  alert('event listeners ')
})

2. DOM node operation

(1) Common node acquisition methods

name

describe

getElementById()

Gets the node with the specified id

getElementsByTagName()

Gets the collection of nodes with the specified tag name

querySelector()

Gets the first node that matches the specified selector or selector group

querySelectorAll()

Gets a collection of all nodes that match the specified selector or selector group

(2) Common node information acquisition methods

name

describe

innerHTML

Returns all HTML content (text and tags) contained within the element, of type string

parentNode

Returns the parent node of the specified node

children

Returns the collection of child element nodes of the specified element

firstElementChild

Returns the first child element node of the specified element

lastElementChild

Returns the last child element node of the specified element

(3) Common methods of obtaining node attributes

name

describe

getAttribute()

Returns a specified attribute value of an element

Get directly using the attribute name

Applicable to some attributes (e.g. title, value, href)

(4) DOM modification

name

describe

innerHTML

innerHTML can not only obtain the element content, but also modify the content in the element through assignment. If the modified content contains html, the string will be parsed into html elements

setAttribute(name,value)

Sets an attribute value on the specified element. If the attribute already exists, update the value; Otherwise, add a new attribute with the specified name and value

Change properties by property name

Reassign the element attribute to change the corresponding attribute value

(5) DOM add

name

describe

createElement(tagName)

Create an HTML element specified by the tag name tagName

appendChild(node)

Inserts a node at the end of the child node list of the specified parent node

insertAdjacentHTML(position, text)

Parse the specified text into HTML string and insert it into the specified location (IE unfriendly)

Position (position of the content relative to the current element):

  • 'before begin': before the element itself

  • 'after begin': before inserting the first child node inside the element

  • 'before end': after inserting the last child node inside the element

  • 'after end': after the element itself

(6) DOM deletion

name

describe

removeChild(child)

To delete the selected child node, you need to specify its parent element

remove()

Delete selected node (IE unfriendly)

3. DOM controls CSS Style

(1) Control the style through the style attribute

box.style.color = "#fff "; / / set the text in the element to white 
box.style.marginLeft = "100px"; //Set the left outer margin of the element to 100px 

(2) Control style through classList:

name

describe

add(class1, class2, ...)

Add one or more class names

remove(class1, class2, ...)

Remove one or more class names

replace(oldClass, newClass)

Replace class name

contains(class)

Determines whether the class name exists and returns a Boolean value

toggle(class, true|false)

If the class name exists, it will be removed, otherwise it will be added. The second parameter means to force the addition (true) or deletion (false) regardless of whether the class name exists or not

3, Complete code + detailed comments

<!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>My memo</title>
  <style>
    button {
      cursor: pointer;
    }

    input {
      outline: none;
      background-color: antiquewhite;
      border: none;
      border-radius: 3px;
      width: 250px;
      height: 30px;
      margin: 15px;
    }

    input::-webkit-input-placeholder {
      color: #999;
    }

    /* Solve the problem that the points in front of li still occupy space after being deleted */
    ul {
      padding: 0;
      margin: 0;
    }

    ul>li {
      list-style: none;
    }

    .border {
      width: 500px;
      background-color: #999;
      border-radius: 20px;
      margin: auto;
      padding-bottom: 20px;
    }

    .border .title {
      font-size: 24px;
      color: aliceblue;
      line-height: 50px;
      text-align: center;
    }

    .form {
      width: 80%;
      margin: 15px auto;
    }

    .form #add {
      width: 100px;
      height: 30px;
      border-radius: 5px;
      border: 0;
      font-weight: 600;
      font-size: 16px;
      color: #999;
      letter-spacing: 6px;
    }

    /* Each li represents each event */
    .item {
      display: flex;
      justify-content: space-between;
      line-height: 30px;
      font-size: 14px;
      color: rgb(75, 73, 73);
      padding: 5px 0;
      border-bottom: 1px solid white;
    }

    .item .info {
      margin-left: 10px;
    }

    .list .item .edit,
    .fin,
    .del {
      width: 50px;
      height: 30px;
      border: 0;
      border-radius: 5px;
      color: white;
    }

    .edit {
      background-color: #337ab7;
    }

    .fin {
      background-color: #20c248;
    }

    .del {
      background-color: #d9534f;
    }

    .btn {
      display: inline-block;
      width: 180px;
      margin-right: 0;
    }

    /* Click the finish button to add the new class name finished */
    .finished {
      color: rgb(112, 110, 110);
      background-color: rgb(197, 190, 190);
      border-radius: 3px
    }

    .finished>.info {
      /* Add strikeouts to text */
      text-decoration: line-through;
    }
  </style>
</head>

<body>
  <!-- Memo outer border -->
  <div class="border">
    <!-- title -->
    <div class="title">My memo</div>
    <hr>
    <!-- Input boxes and buttons -->
    <div class="form">
      <input type="text" name="text" placeholder="Please fill in your event">
      <button id="add">add to</button>
    </div>

    <!-- Memo event list -->
    <div
      style="width: 94%;margin: auto;border-radius: 3px;box-shadow: 2px 2px rgb(119, 115, 115);background-color: rgb(214, 219, 219);">
      <ul class="list">
        <li class="item">
          <!-- Event area -->
          <span class="info">Event 1</span>
          <!-- Button area -->
          <div class="btn">
            <button class="edit">edit</button>
            <button class="fin">complete</button>
            <button class="del">delete</button>
          </div>
        </li>
        <li class="item">
          <!-- Event area -->
          <span class="info">Event 2</span>
          <!-- Button area -->
          <div class="btn">
            <button class="edit">edit</button>
            <button class="fin">complete</button>
            <button class="del">delete</button>
          </div>
        </li>
      </ul>
    </div>
  </div>
</body>

<script>
  var input = document.querySelector('.form input'); //Get event input box
  var addBtn = document.querySelector('#add'); // Get add button
  var list = document.querySelector('.list'); //Get event list ul

  //Click the Add button
  addBtn.addEventListener('click', function () { //Using listener addEventListener
    //Use DOM to add insertAdjacentHTML. The first parameter: the location of the addition; Second parameter: added content
    //Each added li is added before the first li in the ul (after begin)
    list.insertAdjacentHTML('afterbegin', `
    <li class="item">
          <!-- Event area -->
          <span class="info">${input.value}</span>
          <!-- Button area -->
          <div class="btn">
            <button class="edit">edit</button>
            <button class="fin">complete</button>
            <button class="del">delete</button>
          </div>
        </li>
    `);

    //Due to the previous settings, after clicking the Add button, the new element item will be added before the first child node inside the inserted element
    //Therefore, we should operate on the first child element node of the list, otherwise the new event cannot be deleted, modified and completed
    //delete
    list.firstElementChild.querySelector('.del').addEventListener('click', function () {
      var item = this.parentNode.parentNode
      item.remove()
    })
    //complete
    list.firstElementChild.querySelector('.fin').addEventListener('click', function () {
      var item = this.parentNode.parentNode
      item.classList.add('finished')
    })
    //modify
    list.firstElementChild.querySelector('.edit').addEventListener('click', function () {
      var item = this.parentNode.parentNode
      item.querySelector('.info').innerText = prompt('Please modify your event:')
    })
  })

  var delBtns = document.querySelectorAll('.del'); //Get delete button
  var finBtns = document.querySelectorAll('.fin'); //Get Finish button
  var editBtns = document.querySelectorAll('.edit'); //Get Edit button

  //Traversal, several delete buttons are equivalent to several events (li)
  for (var idx = 0; idx < delBtns.length; idx++) {
    //Click the delete button
    delBtns[idx].addEventListener('click', function () {
      var item = this.parentNode.parentNode //Delete the parent of the button parent, that is, the li with the class name item (the line where the button is located), and a li is an event line
      item.remove(); //C li ck the delete button to delete this item
    })

    //Click the finish button
    finBtns[idx].addEventListener('click', function () {
      var item = this.parentNode.parentNode; //Get the event line
      //The classList element can return an attribute collection
      item.classList.add('finished'); //After clicking the finish button, add a new class name finished for this line to implement the new style
    })

    //Click the Edit button
    editBtns[idx].addEventListener('click', function () {
      var item = this.parentNode.parentNode; //Get the event line
      item.querySelector('.info').innerText = prompt('Please modify your event:'); //Click Edit to insert the content into span with the class name info and pop up the system prompt box
    })
  }
</script>

</html>

Topics: Javascript Front-end html5 html