1625479571
Introduction
Front End Development Tool is a software application that helps developers to create beautiful website layouts and apps very easily. In a digital world, new tools and software keep coming up on daily basis. Updates of existing tools also help developers to do tasks easily. Developers select tools and software that are fast, smooth, and reliable to use.
There are various tools and software present but selecting the best of them is not an easy task. Sometimes you have to use multiple tools at a time. Tools should be able to provide fast web development at minimum cost. It should able to help the developer to create a responsive design. Cost-viability, Ease of utilization, Scalability, Portability, and Customization are the components that ought to be thought of while picking a Web Development Tool. Here is a list of the top front-end development tools that should be used in 2021.
Conclusion
Easy to use code, fast and free templates, collaborative tools helps a developer to easily solve frontend development issues and can help in creating fast and responsive web apps. For website creation, developers write long codes, learn html tutorial for beginners and it takes a lot of time but by using these tools, developers can create a web app easily and it saves money and time as well. This software empowers developers to concentrate on the important aspect of a website and helps to identify the problems. Using various community supports and forums you can easily resolve your problems.
Originally shared:- https://sites.google.com/view/hardyian/blog-post
1603587600
Nowadays, creating a blog is easy. But, with all the different options available, you might go crazy by just doing the research.
Should you choose WordPress and tweak the theme to get it the way you like, or a static site generator with no admin interface and complicated build processes?
All you want is a simple blog where you can write about the shit you love.
So why can’t it be simpler? Well, now it is with the DevDojo Dev Blog!
Your Dev Blog will have a default subdomain username.devdojo.com
, and you may choose to add a custom domain as well.
If you wish to use a custom domain, add a CNAME record to your Cloudflare DNS, with your subdomain in the CONTENT section. Wait a few minutes and you’ll have your custom domain resolving in minutes.
Want a video on how to do this, You got it!
At the moment of writing this, there are 2 themes you can choose from (many more to come). Each theme will have a light/dark mode and is built for speed!
Themes are built using the awesome TailwindCSS library. If you pair that with PurgeCSS, minimal javascript, and Cloudflare caching. That’s just a recipe for a fast website.
#developer-blog #dev-blog #web-development #portfolio #blog #blogging #developer-tools #writing
1646142085
In this blog you’ll learn how to create Pure CSS Tabs with Indicator using only HTML & CSS.
To create pure CSS tabs with Indicator using only HTML & CSS. First, you need to create two Files one HTML File and another one is CSS File.
1: First, create an HTML file with the name of index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pure CSS Tabs Design | Codequs</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
<div class="wrapper">
<header>Pure CSS Tabs</header>
<input type="radio" name="slider" checked id="home">
<input type="radio" name="slider" id="blog">
<input type="radio" name="slider" id="code">
<input type="radio" name="slider" id="help">
<input type="radio" name="slider" id="about">
<nav>
<label for="home" class="home"><i class="fas fa-home"></i>Home</label>
<label for="blog" class="blog"><i class="fas fa-blog"></i>Blog</label>
<label for="code" class="code"><i class="fas fa-code"></i>Code</label>
<label for="help" class="help"><i class="far fa-envelope"></i>Help</label>
<label for="about" class="about"><i class="far fa-user"></i>About</label>
<div class="slider"></div>
</nav>
<section>
<div class="content content-1">
<div class="title">This is a Home content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vero aspernatur nobis provident dolores molestias quia quisquam laborum, inventore quis, distinctioa, fugit repudiandae delectus sunt ipsam! Odio illo at quia doloremque fugit iops, asperiores? Consectetur esse officia labore voluptatum blanditiis molestias dic voluptas est, minima unde sequi, praesentium dicta suscipit quisquam iure sed, nemo.</p>
</div>
<div class="content content-2">
<div class="title">This is a Blog content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit amet. Possimus doloris nesciunt mollitia culpa sint itaque, vitae praesentium assumenda suscipit fugit doloremque adipisci doloribus, sequi facere itaque cumque accusamus, quam molestias sed provident quibusdam nam deleniti. Autem eaque aut impedit eo nobis quia, eos sequi tempore! Facere ex repellendus, laboriosam perferendise. Enim quis illo harum, exercitationem nam totam fugit omnis natus quam totam, repudiandae dolor laborum! Commodi?</p>
</div>
<div class="content content-3">
<div class="title">This is a Code content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure, debitis nesciunt! Consectetur officiis, libero nobis dolorem pariatur quisquam temporibus. Labore quaerat neque facere itaque laudantium odit veniam consectetur numquam delectus aspernatur, perferendis repellat illo sequi excepturi quos ipsam aliquid est consequuntur.</p>
</div>
<div class="content content-4">
<div class="title">This is a Help content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim reprehenderit null itaq, odio repellat asperiores vel voluptatem magnam praesentium, eveniet iure ab facere officiis. Quod sequi vel, rem quam provident soluta nihil, eos. Illo oditu omnis cumque praesentium voluptate maxime voluptatibus facilis nulla ipsam quidem mollitia! Veniam, fuga, possimus. Commodi, fugiat aut ut quorioms stu necessitatibus, cumque laborum rem provident tenetur.</p>
</div>
<div class="content content-5">
<div class="title">This is a About content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur officia sequi aliquam. Voluptatem distinctio nemo culpa veritatis nostrum fugit rem adipisci ea ipsam, non veniam ut aspernatur aperiam assumenda quis esse soluta vitae, placeat quasi. Iste dolorum asperiores hic impedit nesciunt atqu, officia magnam commodi iusto aliquid eaque, libero.</p>
</div>
</section>
</div>
</body>
</html>
2: Second, create a CSS file with the name of style.css
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body{
overflow: hidden;
padding: 0 20px;
background: #17a2b8;
}
::selection{
background: rgba(23,162,184,0.3);
}
.wrapper{
max-width: 700px;
width: 100%;
margin: 200px auto;
padding: 25px 30px 30px 30px;
border-radius: 5px;
background: #fff;
box-shadow: 0px 10px 15px rgba(0,0,0,0.1);
}
.wrapper header{
font-size: 30px;
font-weight: 600;
padding-bottom: 20px;
}
.wrapper nav{
position: relative;
width: 80%;
height: 50px;
display: flex;
align-items: center;
}
.wrapper nav label{
display: block;
height: 100%;
width: 100%;
text-align: center;
line-height: 50px;
cursor: pointer;
position: relative;
z-index: 1;
color: #17a2b8;
font-size: 17px;
border-radius: 5px;
margin: 0 5px;
transition: all 0.3s ease;
}
.wrapper nav label:hover{
background: rgba(23,162,184,0.3);
}
#home:checked ~ nav label.home,
#blog:checked ~ nav label.blog,
#code:checked ~ nav label.code,
#help:checked ~ nav label.help,
#about:checked ~ nav label.about{
color: #fff;
}
nav label i{
padding-right: 7px;
}
nav .slider{
position: absolute;
height: 100%;
width: 20%;
left: 0;
bottom: 0;
z-index: 0;
border-radius: 5px;
background: #17a2b8;
transition: all 0.3s ease;
}
input[type="radio"]{
display: none;
}
#blog:checked ~ nav .slider{
left: 20%;
}
#code:checked ~ nav .slider{
left: 40%;
}
#help:checked ~ nav .slider{
left: 60%;
}
#about:checked ~ nav .slider{
left: 80%;
}
section .content{
display: none;
background: #fff;
}
#home:checked ~ section .content-1,
#blog:checked ~ section .content-2,
#code:checked ~ section .content-3,
#help:checked ~ section .content-4,
#about:checked ~ section .content-5{
display: block;
}
section .content .title{
font-size: 21px;
font-weight: 500;
margin: 30px 0 10px 0;
}
section .content p{
text-align: justify;
}
Now you’ve successfully created Pure CSS Tabs with Slide Indicator.
1650865080
Hôm nay chúng ta sẽ học cách thực hiện các Thao tác CRUD trong JavaScript bằng cách tạo Ứng dụng Todo. Bắt đầu thôi 🔥
Đây là ứng dụng chúng tôi tạo ra hôm nay:
CRUD là viết tắt của -
CRUD là một loại cơ chế cho phép bạn tạo dữ liệu, đọc dữ liệu, chỉnh sửa và xóa các dữ liệu đó. Trong trường hợp của chúng tôi, chúng tôi sẽ tạo một ứng dụng Todo, vì vậy chúng tôi sẽ có 4 tùy chọn để tạo tác vụ, đọc tác vụ, cập nhật tác vụ hoặc xóa tác vụ.
Trước khi bắt đầu hướng dẫn, trước tiên, chúng ta hãy hiểu các nguyên tắc CRUD. Để làm được điều đó, hãy tạo một Ứng dụng Truyền thông Xã hội rất đơn giản.
Đối với dự án này, chúng tôi sẽ thực hiện theo các bước sau:
Bên trong thẻ body, hãy tạo một div có tên lớp .container
. Ở đó, chúng ta sẽ có 2 phần, .left
và .right
👇
<body>
<h1>Social Media App</h1>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
Ở phía bên trái, chúng tôi sẽ tạo các bài đăng của chúng tôi. Ở phía bên phải, chúng ta có thể xem, cập nhật và xóa các bài đăng của mình. Bây giờ, hãy tạo một biểu mẫu bên trong thẻ div .left 👇
<div class="left">
<form id="form">
<label for="post"> Write your post here</label>
<br><br>
<textarea name="post" id="input" cols="30" rows="10"></textarea>
<br> <br>
<div id="msg"></div>
<button type="submit">Post</button>
</form>
</div>
Viết mã này bên trong HTML để chúng tôi có thể hiển thị bài đăng của mình ở phía bên phải 👇
<div class="right">
<h3>Your posts here</h3>
<div id="posts"></div>
</div>
Tiếp theo, chúng tôi sẽ chèn CDN phông chữ tuyệt vời bên trong thẻ head để sử dụng phông chữ của nó trong dự án của chúng tôi 👇
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
Bây giờ, chúng tôi sẽ tạo một số bài đăng mẫu với các biểu tượng xóa và chỉnh sửa. Viết mã này bên trong div với id #posts: 👇
<div id="posts">
<div>
<p>Hello world post 1</p>
<span class="options">
<i class="fas fa-edit"></i>
<i class="fas fa-trash-alt"></i>
</span>
</div>
<div >
<p>Hello world post 2</p>
<span class="options">
<i class="fas fa-edit"></i>
<i class="fas fa-trash-alt"></i>
</span>
</div>
</div>
Kết quả cho đến nay trông như thế này:
Hãy giữ nó đơn giản. Viết các kiểu này bên trong bảng định kiểu của bạn: 👇
body {
font-family: sans-serif;
margin: 0 50px;
}
.container {
display: flex;
gap: 50px;
}
#posts {
width: 400px;
}
i {
cursor: pointer;
}
Bây giờ, hãy viết các kiểu này cho các biểu tượng div và tùy chọn của bài đăng: 👇
#posts div {
display: flex;
align-items: center;
justify-content: space-between;
}
.options {
display: flex;
gap: 25px;
}
#msg {
color: red;
}
Kết quả cho đến nay trông như thế này: 👇
Theo biểu đồ này, chúng tôi sẽ tiếp tục với dự án. Đừng lo lắng, tôi sẽ giải thích mọi thứ trên đường đi. 👇
Đầu tiên, hãy nhắm mục tiêu tất cả các bộ chọn ID từ HTML trong JavaScript. Như thế này: 👇
let form = document.getElementById("form");
let input = document.getElementById("input");
let msg = document.getElementById("msg");
let posts = document.getElementById("posts");
Sau đó, xây dựng trình xử lý sự kiện gửi cho biểu mẫu để biểu mẫu có thể ngăn chặn hành vi mặc định của Ứng dụng của chúng tôi. Đồng thời, chúng ta sẽ tạo một hàm có tên formValidation
. 👇
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("button clicked");
formValidation();
});
let formValidation = () => {};
Bây giờ, chúng ta sẽ tạo một câu lệnh if else bên trong formValidation
hàm của chúng ta. Điều này sẽ giúp chúng tôi ngăn người dùng gửi các trường nhập trống. 👇
let formValidation = () => {
if (input.value === "") {
msg.innerHTML = "Post cannot be blank";
console.log("failure");
} else {
console.log("successs");
msg.innerHTML = "";
}
};
Đây là kết quả cho đến nay: 👇
Như bạn có thể thấy, một thông báo cũng sẽ hiển thị nếu người dùng cố gắng gửi biểu mẫu trống.
Bất kỳ dữ liệu nào chúng tôi nhận được từ các trường đầu vào, chúng tôi sẽ lưu trữ chúng trong một đối tượng. Hãy tạo một đối tượng có tên data
. Và, tạo một hàm có tên acceptData
: 👇
let data = {};
let acceptData = () => {};
Ý tưởng chính là, bằng cách sử dụng hàm, chúng tôi thu thập dữ liệu từ các đầu vào và lưu trữ chúng trong đối tượng được đặt tên của chúng tôi data
. Bây giờ chúng ta hãy hoàn thành việc xây dựng acceptData
chức năng của chúng ta.
let acceptData = () => {
data["text"] = input.value;
console.log(data);
};
Ngoài ra, chúng ta cần acceptData
chức năng hoạt động khi người dùng nhấp vào nút gửi. Vì vậy, chúng ta sẽ kích hoạt hàm này trong câu lệnh else của formValidation
hàm của chúng ta. 👇
let formValidation = () => {
if (input.value === "") {
// Other codes are here
} else {
// Other codes are here
acceptData();
}
};
Khi chúng tôi nhập dữ liệu và gửi biểu mẫu, trên bảng điều khiển, chúng tôi có thể thấy một đối tượng chứa các giá trị đầu vào của người dùng của chúng tôi. Như thế này: 👇
Để đăng dữ liệu đầu vào của chúng tôi ở phía bên phải, chúng tôi cần tạo một phần tử div và nối nó vào div bài viết. Đầu tiên, hãy tạo một hàm và viết những dòng sau: 👇
let createPost = () => {
posts.innerHTML += ``;
};
Các dấu gạch ngược là các ký tự mẫu. Nó sẽ hoạt động như một mẫu cho chúng tôi. Ở đây, chúng ta cần 3 thứ: div cha, chính đầu vào và div tùy chọn mang các biểu tượng chỉnh sửa và xóa. Hãy hoàn thành chức năng của chúng ta 👇
let createPost = () => {
posts.innerHTML += `
<div>
<p>${data.text}</p>
<span class="options">
<i onClick="editPost(this)" class="fas fa-edit"></i>
<i onClick="deletePost(this)" class="fas fa-trash-alt"></i>
</span>
</div>
`;
input.value = "";
};
Trong acceptdata
chức năng của chúng tôi, chúng tôi sẽ kích createPost
hoạt chức năng của mình. Như thế này: 👇
let acceptData = () => {
// Other codes are here
createPost();
};
Kết quả cho đến nay: 👇
Cho đến nay, các bạn tốt, chúng ta gần như đã hoàn thành xong dự án 1.
Để xóa một bài đăng, trước hết, hãy tạo một hàm bên trong tệp javascript của chúng tôi:
let deletePost = (e) => {};
Tiếp theo, chúng tôi kích deletePost
hoạt chức năng này bên trong tất cả các biểu tượng xóa của chúng tôi bằng cách sử dụng thuộc tính onClick. Bạn sẽ viết những dòng này bằng HTML và trên mẫu. 👇
<i onClick="deletePost(this)" class="fas fa-trash-alt"></i>
Từ this
khóa sẽ tham chiếu đến phần tử đã kích hoạt sự kiện. trong trường hợp của chúng tôi, this
đề cập đến nút xóa.
Hãy xem xét kỹ, cha của nút xóa là khoảng cách với các tùy chọn tên lớp. Cha của span là div. Vì vậy, chúng tôi viết parentElement
hai lần để chúng tôi có thể chuyển từ biểu tượng xóa sang div và nhắm mục tiêu trực tiếp để xóa nó.
Hãy hoàn thành chức năng của chúng ta. 👇
let deletePost = (e) => {
e.parentElement.parentElement.remove();
};
Kết quả cho đến nay: 👇
Để chỉnh sửa một bài đăng, trước hết, hãy tạo một hàm bên trong tệp JavaScript của chúng tôi:
let editPost = (e) => {};
Tiếp theo, chúng tôi kích editPost
hoạt chức năng này bên trong tất cả các biểu tượng chỉnh sửa của chúng tôi bằng cách sử dụng thuộc tính onClick. Bạn sẽ viết những dòng này bằng HTML và trên mẫu. 👇
<i onClick="editPost(this)" class="fas fa-edit"></i>
Từ this
khóa sẽ tham chiếu đến phần tử đã kích hoạt sự kiện. Trong trường hợp của chúng tôi, tham chiếu this
đến nút chỉnh sửa.
Xem kỹ, cha của nút chỉnh sửa là khoảng cách với các tùy chọn tên lớp. Cha của span là div. Vì vậy, chúng tôi viết parentElement
hai lần để chúng tôi có thể chuyển từ biểu tượng chỉnh sửa sang div và nhắm mục tiêu trực tiếp để xóa nó.
Sau đó, bất kỳ dữ liệu nào có trong bài đăng, chúng tôi đưa dữ liệu đó trở lại trường đầu vào để chỉnh sửa.
Hãy hoàn thành chức năng của chúng ta. 👇
let editPost = (e) => {
input.value = e.parentElement.previousElementSibling.innerHTML;
e.parentElement.parentElement.remove();
};
Kết quả cho đến nay: 👇
Xin chúc mừng mọi người đã hoàn thành dự án 1. Bây giờ, hãy nghỉ ngơi một chút!
Cách tạo ứng dụng việc cần làm bằng Thao tác CRUD
Hãy bắt đầu làm dự án 2, đó là Ứng dụng việc cần làm.
Đối với dự án này, chúng tôi sẽ thực hiện theo các bước sau:
Viết mã khởi động này bên trong tệp HTML: 👇
<div class="app">
<h4 class="mb-3">TODO App</h4>
<div id="addNew" data-bs-toggle="modal" data-bs-target="#form">
<span>Add New Task</span>
<i class="fas fa-plus"></i>
</div>
</div>
Div có id addNew
là nút sẽ mở phương thức. Khoảng cách sẽ được hiển thị trên nút. Đây i
là biểu tượng từ phông chữ tuyệt vời.
Chúng tôi sẽ sử dụng bootstrap để làm phương thức của chúng tôi. Chúng tôi sẽ sử dụng phương thức để thêm các nhiệm vụ mới. Đối với điều đó, hãy thêm liên kết bootstrap CDN bên trong thẻ head. 👇
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
Để xem các tác vụ đã tạo, chúng tôi sẽ sử dụng một div với một nhiệm vụ id, bên trong div có ứng dụng tên lớp. 👇
<h5 class="text-center my-3">Tasks</h5>
<div id="tasks"></div>
Chèn CDN phông chữ tuyệt vời bên trong thẻ head để sử dụng phông chữ trong dự án của chúng tôi 👇
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
Sao chép và dán mã bên dưới từ phương thức bootstrap. Nó mang một biểu mẫu với 3 trường đầu vào và một nút gửi. Nếu muốn, bạn có thể tìm kiếm trang web của Bootstrap bằng cách viết 'modal' vào thanh tìm kiếm.
<!-- Modal -->
<form
class="modal fade"
id="form"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Task</h5>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div class="modal-body">
<p>Task Title</p>
<input type="text" class="form-control" name="" id="textInput" />
<div id="msg"></div>
<br />
<p>Due Date</p>
<input type="date" class="form-control" name="" id="dateInput" />
<br />
<p>Description</p>
<textarea
name=""
class="form-control"
id="textarea"
cols="30"
rows="5"
></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
Close
</button>
<button type="submit" id="add" class="btn btn-primary">Add</button>
</div>
</div>
</div>
</form>
Kết quả cho đến nay: 👇
Chúng tôi đã hoàn tất việc thiết lập tệp HTML. Hãy bắt đầu CSS.
Thêm các kiểu này vào phần nội dung để chúng tôi có thể giữ ứng dụng của mình ở chính giữa màn hình.
body {
font-family: sans-serif;
margin: 0 50px;
background-color: #e5e5e5;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Hãy tạo kiểu div với ứng dụng classname. 👇
.app {
background-color: #fff;
width: 300px;
height: 500px;
border: 5px solid #abcea1;
border-radius: 8px;
padding: 15px;
}
Kết quả cho đến nay: 👇
Bây giờ, hãy tạo kiểu cho nút với id addNew
. 👇
#addNew {
display: flex;
justify-content: space-between;
align-items: center;
background-color: rgba(171, 206, 161, 0.35);
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
}
.fa-plus {
background-color: #abcea1;
padding: 3px;
border-radius: 3px;
}
Kết quả cho đến nay: 👇
Nếu bạn nhấp vào nút, phương thức sẽ bật lên như thế này: 👇
Trong tệp JavaScript, trước hết, hãy chọn tất cả các bộ chọn từ HTML mà chúng ta cần sử dụng. 👇
let form = document.getElementById("form");
let textInput = document.getElementById("textInput");
let dateInput = document.getElementById("dateInput");
let textarea = document.getElementById("textarea");
let msg = document.getElementById("msg");
let tasks = document.getElementById("tasks");
let add = document.getElementById("add");
Chúng tôi không thể để người dùng gửi các trường đầu vào trống. Vì vậy, chúng ta cần xác thực các trường đầu vào. 👇
form.addEventListener("submit", (e) => {
e.preventDefault();
formValidation();
});
let formValidation = () => {
if (textInput.value === "") {
console.log("failure");
msg.innerHTML = "Task cannot be blank";
} else {
console.log("success");
msg.innerHTML = "";
}
};
Ngoài ra, hãy thêm dòng này vào bên trong CSS:
#msg {
color: red;
}
Kết quả cho đến nay: 👇
Như bạn có thể thấy, xác thực đang hoạt động. Mã JavaScript không cho phép người dùng gửi các trường nhập trống, nếu không bạn sẽ thấy thông báo lỗi.
Bất kỳ đầu vào nào mà người dùng viết, chúng tôi cần thu thập chúng và lưu trữ chúng trong bộ nhớ cục bộ.
Đầu tiên, chúng tôi thu thập dữ liệu từ các trường đầu vào, sử dụng hàm được đặt tên acceptData
và một mảng được đặt tên data
. Sau đó, chúng tôi đẩy chúng vào bên trong bộ nhớ cục bộ như thế này: 👇
let data = [];
let acceptData = () => {
data.push({
text: textInput.value,
date: dateInput.value,
description: textarea.value,
});
localStorage.setItem("data", JSON.stringify(data));
console.log(data);
};
Cũng lưu ý rằng điều này sẽ không bao giờ hoạt động trừ khi bạn gọi hàm acceptData
bên trong câu lệnh else của xác thực biểu mẫu. Cùng theo dõi tại đây: 👇
let formValidation = () => {
// Other codes are here
else {
// Other codes are here
acceptData();
}
};
Bạn có thể nhận thấy rằng phương thức không tự động đóng. Để giải quyết vấn đề này, hãy viết hàm nhỏ này bên trong câu lệnh else của xác thực biểu mẫu: 👇
let formValidation = () => {
// Other codes are here
else {
// Other codes are here
acceptData();
add.setAttribute("data-bs-dismiss", "modal");
add.click();
(() => {
add.setAttribute("data-bs-dismiss", "");
})();
}
};
Nếu bạn mở các công cụ dành cho nhà phát triển Chrome, hãy chuyển đến ứng dụng và mở bộ nhớ cục bộ. Bạn có thể xem kết quả này: 👇
Để tạo một tác vụ mới, chúng ta cần tạo một hàm, sử dụng các ký tự mẫu để tạo các phần tử HTML và sử dụng bản đồ để đẩy dữ liệu được thu thập từ người dùng vào bên trong mẫu. Cùng theo dõi tại đây: 👇
let createTasks = () => {
tasks.innerHTML = "";
data.map((x, y) => {
return (tasks.innerHTML += `
<div id=${y}>
<span class="fw-bold">${x.text}</span>
<span class="small text-secondary">${x.date}</span>
<p>${x.description}</p>
<span class="options">
<i onClick= "editTask(this)" data-bs-toggle="modal" data-bs-target="#form" class="fas fa-edit"></i>
<i onClick ="deleteTask(this);createTasks()" class="fas fa-trash-alt"></i>
</span>
</div>
`);
});
resetForm();
};
Cũng lưu ý rằng hàm sẽ không bao giờ chạy trừ khi bạn gọi nó bên trong acceptData
hàm, như thế này: 👇
let acceptData = () => {
// Other codes are here
createTasks();
};
Khi chúng tôi đã hoàn tất việc thu thập và chấp nhận dữ liệu từ người dùng, chúng tôi cần xóa các trường đầu vào. Đối với điều đó, chúng tôi tạo ra một hàm được gọi là resetForm
. Cùng theo dõi: 👇
let resetForm = () => {
textInput.value = "";
dateInput.value = "";
textarea.value = "";
};
Kết quả cho đến nay: 👇
Như bạn có thể thấy, không có phong cách nào với thẻ. Hãy thêm một số phong cách: 👇
#tasks {
display: grid;
grid-template-columns: 1fr;
gap: 14px;
}
#tasks div {
border: 3px solid #abcea1;
background-color: #e2eede;
border-radius: 6px;
padding: 5px;
display: grid;
gap: 4px;
}
Tạo kiểu cho các nút chỉnh sửa và xóa bằng mã này: 👇
#tasks div .options {
justify-self: center;
display: flex;
gap: 20px;
}
#tasks div .options i {
cursor: pointer;
}
Kết quả cho đến nay: 👇
Xem kỹ ở đây, tôi đã thêm 3 dòng mã bên trong hàm.
let deleteTask = (e) => {
e.parentElement.parentElement.remove();
data.splice(e.parentElement.parentElement.id, 1);
localStorage.setItem("data", JSON.stringify(data));
console.log(data);
};
Bây giờ, hãy tạo một tác vụ giả và cố gắng xóa nó. Kết quả cho đến nay trông như thế này: 👇
Hãy xem kỹ ở đây, tôi đã thêm 5 dòng mã bên trong hàm.
let editTask = (e) => {
let selectedTask = e.parentElement.parentElement;
textInput.value = selectedTask.children[0].innerHTML;
dateInput.value = selectedTask.children[1].innerHTML;
textarea.value = selectedTask.children[2].innerHTML;
deleteTask(e);
};
Bây giờ, hãy thử tạo một tác vụ giả và chỉnh sửa nó. Kết quả cho đến nay: 👇
Nếu bạn làm mới trang, bạn sẽ lưu ý rằng tất cả dữ liệu của bạn đã biến mất. Để giải quyết vấn đề đó, chúng tôi chạy IIFE (Biểu thức hàm được gọi ngay lập tức) để truy xuất dữ liệu từ bộ nhớ cục bộ. Cùng theo dõi: 👇
(() => {
data = JSON.parse(localStorage.getItem("data")) || [];
console.log(data);
createTasks();
})();
Bây giờ dữ liệu sẽ hiển thị ngay cả khi bạn làm mới trang.
Xin chúc mừng vì đã hoàn thành thành công hướng dẫn này. Bạn đã học cách tạo một ứng dụng danh sách việc cần làm bằng các phép toán CRUD. Bây giờ, bạn có thể tạo ứng dụng CRUD của riêng mình bằng cách sử dụng hướng dẫn này.
Nguồn: https://www.freecodecamp.org/news/learn-crud-operations-in-javascript-by-building-todo-app/
1650009780
Today we're gonna learn how to do CRUD Operations in JavaScript by making a Todo App. Let's get started 🔥
This is the app we're making today:
CRUD stands for -
CRUD is a type of mechanism that allows you to create data, read data, edit it, and delete those data. In our case, we're gonna make a Todo app, so we will have 4 options to create tasks, read tasks, update tasks, or delete tasks.
Before starting the tutorial, first, let's understand the CRUD principles. For that, let's create a very very simple Social Media Application.
For this project, we will be following these steps below:
Inside the body tag, create a div with a class name .container
. There, we will have 2 sections, .left
and .right
👇
<body>
<h1>Social Media App</h1>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
On the left side, we will create our posts. On the right side, we can see, update, and delete our posts. Now, create a form inside the .left div tag 👇
<div class="left">
<form id="form">
<label for="post"> Write your post here</label>
<br><br>
<textarea name="post" id="input" cols="30" rows="10"></textarea>
<br> <br>
<div id="msg"></div>
<button type="submit">Post</button>
</form>
</div>
Write this code inside the HTML so that we can display our post on the right side 👇
<div class="right">
<h3>Your posts here</h3>
<div id="posts"></div>
</div>
Next, we'll insert the font-awesome CDN inside the head tag to use its fonts in our project 👇
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
Now, we're gonna make some sample posts with delete and edit icons. Write this code inside the div with the id #posts: 👇
<div id="posts">
<div>
<p>Hello world post 1</p>
<span class="options">
<i class="fas fa-edit"></i>
<i class="fas fa-trash-alt"></i>
</span>
</div>
<div >
<p>Hello world post 2</p>
<span class="options">
<i class="fas fa-edit"></i>
<i class="fas fa-trash-alt"></i>
</span>
</div>
</div>
The result so far looks like this:
Let's keep it simple. Write these styles inside your stylesheet: 👇
body {
font-family: sans-serif;
margin: 0 50px;
}
.container {
display: flex;
gap: 50px;
}
#posts {
width: 400px;
}
i {
cursor: pointer;
}
Now, write these styles for the post div and option icons: 👇
#posts div {
display: flex;
align-items: center;
justify-content: space-between;
}
.options {
display: flex;
gap: 25px;
}
#msg {
color: red;
}
The results so far look like this:👇
According to this flow chart, we will go forward with the project. Don't worry, I'll explain everything along the way. 👇
First, let's target all the ID selectors from the HTML in JavaScript. Like this: 👇
let form = document.getElementById("form");
let input = document.getElementById("input");
let msg = document.getElementById("msg");
let posts = document.getElementById("posts");
Then, build a submit event listener for the form so that it can prevent the default behaviour of our App. At the same time, we will create a function named formValidation
. 👇
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("button clicked");
formValidation();
});
let formValidation = () => {};
Now, we're gonna make an if else statement inside our formValidation
function. This will help us prevent users from submitting blank input fields. 👇
let formValidation = () => {
if (input.value === "") {
msg.innerHTML = "Post cannot be blank";
console.log("failure");
} else {
console.log("successs");
msg.innerHTML = "";
}
};
Here's the result so far: 👇
As you can see, a message will also show up if the user tries to submit the form blank.
Whatever data we get from the input fields, we will store them in an object. Let's create an object named data
. And, create a function named acceptData
: 👇
let data = {};
let acceptData = () => {};
The main idea is that, using the function, we collect data from the inputs and store them in our object named data
. Now let's finish building our acceptData
function.
let acceptData = () => {
data["text"] = input.value;
console.log(data);
};
Also, we need the acceptData
function to work when the user clicks the submit button. For that, we will fire this function in the else statement of our formValidation
function. 👇
let formValidation = () => {
if (input.value === "") {
// Other codes are here
} else {
// Other codes are here
acceptData();
}
};
When we input data and submit the form, on the console we can see an object holding our user's input values. Like this: 👇
In order to post our input data on the right side, we need to create a div element and append it to the posts div. First, let's create a function and write these lines: 👇
let createPost = () => {
posts.innerHTML += ``;
};
The backticks are template literals. It will work as a template for us. Here, we need 3 things: a parent div, the input itself, and the options div which carries the edit and delete icons. Let's finish our function 👇
let createPost = () => {
posts.innerHTML += `
<div>
<p>${data.text}</p>
<span class="options">
<i onClick="editPost(this)" class="fas fa-edit"></i>
<i onClick="deletePost(this)" class="fas fa-trash-alt"></i>
</span>
</div>
`;
input.value = "";
};
In our acceptdata
function, we will fire our createPost
function. Like this: 👇
let acceptData = () => {
// Other codes are here
createPost();
};
The result so far: 👇
So far so good guys, we're almost done with project 1.
In order to delete a post, first of all, let's create a function inside our javascript file:
let deletePost = (e) => {};
Next up, we fire this deletePost
function inside all of our delete icons using an onClick attribute. You'll write these lines in HTML and on the template literal. 👇
<i onClick="deletePost(this)" class="fas fa-trash-alt"></i>
The this
keyword will refer to the element that fired the event. in our case, the this
refers to the delete button.
Look carefully, the parent of the delete button is the span with class name options. The parent of the span is the div. So, we write parentElement
twice so that we can jump from the delete icon to the div and target it directly to remove it.
Let's finish our function. 👇
let deletePost = (e) => {
e.parentElement.parentElement.remove();
};
The result so far: 👇
In order to edit a post, first of all, let's create a function inside our JavaScript file:
let editPost = (e) => {};
Next up, we fire this editPost
function inside all of our edit icons using an onClick attribute. You'll write these lines in HTML and on the template literal. 👇
<i onClick="editPost(this)" class="fas fa-edit"></i>
The this
keyword will refer to the element that fired the event. In our case, the this
refers to the edit button.
Look carefully, the parent of the edit button is the span with class name options. The parent of the span is the div. So, we write parentElement
twice so that we can jump from the edit icon to the div and target it directly to remove it.
Then, whatever data is inside the post, we bring it back on the input field to edit it.
Let's finish our function. 👇
let editPost = (e) => {
input.value = e.parentElement.previousElementSibling.innerHTML;
e.parentElement.parentElement.remove();
};
The result so far: 👇
Congratulations everyone for completing project 1. Now, take a small break!
How to Make a To-Do App using CRUD Operations
Let's start making project 2, which is a To-Do App.
For this project, we will be following these steps below:
Write this starter code inside the HTML file: 👇
<div class="app">
<h4 class="mb-3">TODO App</h4>
<div id="addNew" data-bs-toggle="modal" data-bs-target="#form">
<span>Add New Task</span>
<i class="fas fa-plus"></i>
</div>
</div>
The div with an id addNew
is the button that will open the modal. The span will be displayed on the button. The i
is the icon from font-awesome.
We're going to use bootstrap to make our modal. We'll use the modal to add new tasks. For that, add the bootstrap CDN link inside the head tag. 👇
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
To see the created tasks, we'll use a div with an id tasks, inside the div with the classname app. 👇
<h5 class="text-center my-3">Tasks</h5>
<div id="tasks"></div>
Insert the font-awesome CDN inside the head tag to use fonts in our project 👇
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
Copy and paste the code below which are from the bootstrap modal. It carries a form with 3 input fields and a submit button. If you want then you can search Bootstrap's website by writing 'modal' in the search bar.
<!-- Modal -->
<form
class="modal fade"
id="form"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Task</h5>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div class="modal-body">
<p>Task Title</p>
<input type="text" class="form-control" name="" id="textInput" />
<div id="msg"></div>
<br />
<p>Due Date</p>
<input type="date" class="form-control" name="" id="dateInput" />
<br />
<p>Description</p>
<textarea
name=""
class="form-control"
id="textarea"
cols="30"
rows="5"
></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
Close
</button>
<button type="submit" id="add" class="btn btn-primary">Add</button>
</div>
</div>
</div>
</form>
The result so far: 👇
We're done with the HTML file setup. Let's start the CSS.
Add these styles in the body so that we can keep our app at the exact center of the screen.
body {
font-family: sans-serif;
margin: 0 50px;
background-color: #e5e5e5;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Let's style the div with the classname app. 👇
.app {
background-color: #fff;
width: 300px;
height: 500px;
border: 5px solid #abcea1;
border-radius: 8px;
padding: 15px;
}
The result so far: 👇
Now, let's style the button with the id addNew
. 👇
#addNew {
display: flex;
justify-content: space-between;
align-items: center;
background-color: rgba(171, 206, 161, 0.35);
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
}
.fa-plus {
background-color: #abcea1;
padding: 3px;
border-radius: 3px;
}
The result so far: 👇
If you click on the button, the modal pops up like this: 👇
In the JavaScript file, first of all, select all the selectors from the HTML that we need to use. 👇
let form = document.getElementById("form");
let textInput = document.getElementById("textInput");
let dateInput = document.getElementById("dateInput");
let textarea = document.getElementById("textarea");
let msg = document.getElementById("msg");
let tasks = document.getElementById("tasks");
let add = document.getElementById("add");
We cannot let a user submit blank input fields. So, we need to validate the input fields. 👇
form.addEventListener("submit", (e) => {
e.preventDefault();
formValidation();
});
let formValidation = () => {
if (textInput.value === "") {
console.log("failure");
msg.innerHTML = "Task cannot be blank";
} else {
console.log("success");
msg.innerHTML = "";
}
};
Also, add this line inside the CSS:
#msg {
color: red;
}
The result so far: 👇
As you can see, the validation is working. The JavaScript code doesn't let the user submit blank input fields, otherwise you're gonna see an error message.
Whatever inputs the user writes, we need to collect them and store them in local storage.
First, we collect the data from the input fields, using the function named acceptData
and an array named data
. Then we push them inside the local storage like this: 👇
let data = [];
let acceptData = () => {
data.push({
text: textInput.value,
date: dateInput.value,
description: textarea.value,
});
localStorage.setItem("data", JSON.stringify(data));
console.log(data);
};
Also note that this will never work unless you invoke the function acceptData
inside the else statement of the form validation. Follow along here: 👇
let formValidation = () => {
// Other codes are here
else {
// Other codes are here
acceptData();
}
};
You may have noticed that the modal doesn't close automatically. To solve this, write this small function inside the else statement of the form validation: 👇
let formValidation = () => {
// Other codes are here
else {
// Other codes are here
acceptData();
add.setAttribute("data-bs-dismiss", "modal");
add.click();
(() => {
add.setAttribute("data-bs-dismiss", "");
})();
}
};
If you open Chrome dev tools, go to the application and open the local storage. You can see this result: 👇
In order to create a new task, we need to create a function, use template literals to create the HTML elements, and use a map to push the data collected from the user inside the template. Follow along here: 👇
let createTasks = () => {
tasks.innerHTML = "";
data.map((x, y) => {
return (tasks.innerHTML += `
<div id=${y}>
<span class="fw-bold">${x.text}</span>
<span class="small text-secondary">${x.date}</span>
<p>${x.description}</p>
<span class="options">
<i onClick= "editTask(this)" data-bs-toggle="modal" data-bs-target="#form" class="fas fa-edit"></i>
<i onClick ="deleteTask(this);createTasks()" class="fas fa-trash-alt"></i>
</span>
</div>
`);
});
resetForm();
};
Also note that the function will never run unless you invoke it inside the acceptData
function, like this: 👇
let acceptData = () => {
// Other codes are here
createTasks();
};
Once we're done collecting and accepting data from the user, we need to clear the input fields. For that we create a function called resetForm
. Follow along: 👇
let resetForm = () => {
textInput.value = "";
dateInput.value = "";
textarea.value = "";
};
The result so far: 👇
As you can see, there's no styles with the card. Let's add some styles: 👇
#tasks {
display: grid;
grid-template-columns: 1fr;
gap: 14px;
}
#tasks div {
border: 3px solid #abcea1;
background-color: #e2eede;
border-radius: 6px;
padding: 5px;
display: grid;
gap: 4px;
}
Style the edit and delete buttons with this code: 👇
#tasks div .options {
justify-self: center;
display: flex;
gap: 20px;
}
#tasks div .options i {
cursor: pointer;
}
The result so far: 👇
Look here carefully, I added 3 lines of code inside the function.
let deleteTask = (e) => {
e.parentElement.parentElement.remove();
data.splice(e.parentElement.parentElement.id, 1);
localStorage.setItem("data", JSON.stringify(data));
console.log(data);
};
Now create a dummy task and try to delete it. The result so far looks like this: 👇
Look here carefully, I added 5 lines of code inside the function.
let editTask = (e) => {
let selectedTask = e.parentElement.parentElement;
textInput.value = selectedTask.children[0].innerHTML;
dateInput.value = selectedTask.children[1].innerHTML;
textarea.value = selectedTask.children[2].innerHTML;
deleteTask(e);
};
Now, try to create a dummy task and edit it. The result so far: 👇
If you refresh the page, you'll note that all of your data is gone. In order to solve that issue, we run a IIFE (Immediately invoked function expression) to retrieve the data from local storage. Follow along: 👇
(() => {
data = JSON.parse(localStorage.getItem("data")) || [];
console.log(data);
createTasks();
})();
Now the data will show up even if you refresh the page.
Congratulations for successfully completing this tutorial. You've learned how to create a todo list application using CRUD operations. Now, you can create your own CRUD application using this tutorial.
Here's your medal for reading until the end. ❤️
Source: https://www.freecodecamp.org/news/learn-crud-operations-in-javascript-by-building-todo-app/
1649978400
Hoy vamos a aprender cómo hacer operaciones CRUD en JavaScript creando una aplicación Todo. Empecemos 🔥
Esta es la aplicación que estamos haciendo hoy:
CRUD significa -
CRUD es un tipo de mecanismo que le permite crear datos, leer datos, editarlos y eliminar esos datos. En nuestro caso, vamos a crear una aplicación Todo, por lo que tendremos 4 opciones para crear tareas, leer tareas, actualizar tareas o eliminar tareas.
Antes de comenzar el tutorial, primero, comprendamos los principios CRUD. Para eso, creemos una aplicación de redes sociales muy, muy simple.
Para este proyecto, seguiremos los siguientes pasos:
Dentro de la etiqueta del cuerpo, crea un div con un nombre de clase .container
. Ahí tendremos 2 secciones, .left
y .right
👇
<body>
<h1>Social Media App</h1>
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
</body>
En el lado izquierdo, crearemos nuestras publicaciones. En el lado derecho, podemos ver, actualizar y eliminar nuestras publicaciones. Ahora, crea un formulario dentro de la etiqueta div .left 👇
<div class="left">
<form id="form">
<label for="post"> Write your post here</label>
<br><br>
<textarea name="post" id="input" cols="30" rows="10"></textarea>
<br> <br>
<div id="msg"></div>
<button type="submit">Post</button>
</form>
</div>
Escribe este código dentro del HTML para que podamos mostrar nuestra publicación en el lado derecho 👇
<div class="right">
<h3>Your posts here</h3>
<div id="posts"></div>
</div>
A continuación, insertaremos el CDN font-awesome dentro de la etiqueta de encabezado para usar sus fuentes en nuestro proyecto 👇
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
Ahora, vamos a hacer algunas publicaciones de muestra con íconos de eliminar y editar. Escribe este código dentro del div con el id #posts: 👇
<div id="posts">
<div>
<p>Hello world post 1</p>
<span class="options">
<i class="fas fa-edit"></i>
<i class="fas fa-trash-alt"></i>
</span>
</div>
<div >
<p>Hello world post 2</p>
<span class="options">
<i class="fas fa-edit"></i>
<i class="fas fa-trash-alt"></i>
</span>
</div>
</div>
El resultado hasta ahora se ve así:
Mantengámoslo simple. Escribe estos estilos dentro de tu hoja de estilo: 👇
body {
font-family: sans-serif;
margin: 0 50px;
}
.container {
display: flex;
gap: 50px;
}
#posts {
width: 400px;
}
i {
cursor: pointer;
}
Ahora, escribe estos estilos para los íconos de opción y div posteriores: 👇
#posts div {
display: flex;
align-items: center;
justify-content: space-between;
}
.options {
display: flex;
gap: 25px;
}
#msg {
color: red;
}
Los resultados hasta ahora se ven así: 👇
De acuerdo con este diagrama de flujo, seguiremos adelante con el proyecto. No te preocupes, te explicaré todo en el camino. 👇
Primero, apuntemos a todos los selectores de ID del HTML en JavaScript. Así: 👇
let form = document.getElementById("form");
let input = document.getElementById("input");
let msg = document.getElementById("msg");
let posts = document.getElementById("posts");
Luego, cree un detector de eventos de envío para el formulario para que pueda evitar el comportamiento predeterminado de nuestra aplicación. Al mismo tiempo, crearemos una función llamada formValidation
. 👇
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("button clicked");
formValidation();
});
let formValidation = () => {};
Ahora, vamos a hacer una declaración if else dentro de nuestra formValidation
función. Esto nos ayudará a evitar que los usuarios envíen campos de entrada en blanco. 👇
let formValidation = () => {
if (input.value === "") {
msg.innerHTML = "Post cannot be blank";
console.log("failure");
} else {
console.log("successs");
msg.innerHTML = "";
}
};
Aquí está el resultado hasta ahora: 👇
Como puede ver, también aparecerá un mensaje si el usuario intenta enviar el formulario en blanco.
Cualesquiera que sean los datos que obtengamos de los campos de entrada, los almacenaremos en un objeto. Vamos a crear un objeto llamado data
. Y crea una función llamada acceptData
: 👇
let data = {};
let acceptData = () => {};
La idea principal es que, usando la función, recopilamos datos de las entradas y los almacenamos en nuestro objeto llamado data
. Ahora terminemos de construir nuestra acceptData
función.
let acceptData = () => {
data["text"] = input.value;
console.log(data);
};
Además, necesitamos que la acceptData
función funcione cuando el usuario haga clic en el botón Enviar. Para eso, activaremos esta función en la instrucción else de nuestra formValidation
función. 👇
let formValidation = () => {
if (input.value === "") {
// Other codes are here
} else {
// Other codes are here
acceptData();
}
};
Cuando ingresamos datos y enviamos el formulario, en la consola podemos ver un objeto que contiene los valores de entrada de nuestro usuario. Así: 👇
Para publicar nuestros datos de entrada en el lado derecho, necesitamos crear un elemento div y agregarlo al div de publicaciones. Primero, creemos una función y escribamos estas líneas: 👇
let createPost = () => {
posts.innerHTML += ``;
};
Los acentos graves son literales de plantilla. Funcionará como una plantilla para nosotros. Aquí, necesitamos 3 cosas: un div principal, la entrada en sí y el div de opciones que lleva los íconos de edición y eliminación. Terminemos nuestra función 👇
let createPost = () => {
posts.innerHTML += `
<div>
<p>${data.text}</p>
<span class="options">
<i onClick="editPost(this)" class="fas fa-edit"></i>
<i onClick="deletePost(this)" class="fas fa-trash-alt"></i>
</span>
</div>
`;
input.value = "";
};
En nuestra acceptdata
función, activaremos nuestra createPost
función. Así: 👇
let acceptData = () => {
// Other codes are here
createPost();
};
El resultado hasta ahora: 👇
Hasta ahora todo bien chicos, casi hemos terminado con el proyecto 1.
Para eliminar una publicación, en primer lugar, creemos una función dentro de nuestro archivo javascript:
let deletePost = (e) => {};
A continuación, activamos esta deletePost
función dentro de todos nuestros íconos de eliminación usando un atributo onClick. Escribirá estas líneas en HTML y en el literal de la plantilla. 👇
<i onClick="deletePost(this)" class="fas fa-trash-alt"></i>
La this
palabra clave se referirá al elemento que disparó el evento. en nuestro caso, el this
se refiere al botón eliminar.
Mire con cuidado, el padre del botón Eliminar es el tramo con opciones de nombre de clase. El padre del lapso es el div. Entonces, escribimos parentElement
dos veces para que podamos saltar del ícono de eliminar al div y apuntarlo directamente para eliminarlo.
Terminemos nuestra función. 👇
let deletePost = (e) => {
e.parentElement.parentElement.remove();
};
El resultado hasta ahora: 👇
Para editar una publicación, en primer lugar, creemos una función dentro de nuestro archivo JavaScript:
let editPost = (e) => {};
A continuación, activamos esta editPost
función dentro de todos nuestros íconos de edición usando un atributo onClick. Escribirá estas líneas en HTML y en el literal de la plantilla. 👇
<i onClick="editPost(this)" class="fas fa-edit"></i>
La this
palabra clave se referirá al elemento que disparó el evento. En nuestro caso, el this
se refiere al botón editar.
Mire con cuidado, el padre del botón de edición es el tramo con opciones de nombre de clase. El padre del lapso es el div. Entonces, escribimos parentElement
dos veces para que podamos saltar del ícono de edición al div y apuntarlo directamente para eliminarlo.
Luego, cualquier dato que esté dentro de la publicación, lo traemos de vuelta al campo de entrada para editarlo.
Terminemos nuestra función. 👇
let editPost = (e) => {
input.value = e.parentElement.previousElementSibling.innerHTML;
e.parentElement.parentElement.remove();
};
El resultado hasta ahora: 👇
Felicitaciones a todos por completar el proyecto 1. Ahora, ¡tómense un pequeño descanso!
Cómo hacer una aplicación de tareas pendientes usando operaciones CRUD
Comencemos a hacer el proyecto 2, que es una aplicación To-Do.
Para este proyecto, seguiremos los siguientes pasos:
Escribe este código de inicio dentro del archivo HTML: 👇
<div class="app">
<h4 class="mb-3">TODO App</h4>
<div id="addNew" data-bs-toggle="modal" data-bs-target="#form">
<span>Add New Task</span>
<i class="fas fa-plus"></i>
</div>
</div>
El div con una identificación addNew
es el botón que abrirá el modal. El intervalo se mostrará en el botón. El i
es el ícono de font-awesome.
Vamos a usar bootstrap para hacer nuestro modal. Usaremos el modal para agregar nuevas tareas. Para eso, agregue el enlace CDN de arranque dentro de la etiqueta principal. 👇
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
Para ver las tareas creadas, usaremos un div con una tarea de identificación, dentro del div con la aplicación de nombre de clase. 👇
<h5 class="text-center my-3">Tasks</h5>
<div id="tasks"></div>
Inserte el CDN font-awesome dentro de la etiqueta principal para usar fuentes en nuestro proyecto 👇
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
Copie y pegue el código a continuación que proviene del modal de arranque. Lleva un formulario con 3 campos de entrada y un botón de envío. Si lo desea, puede buscar en el sitio web de Bootstrap escribiendo 'modal' en la barra de búsqueda.
<!-- Modal -->
<form
class="modal fade"
id="form"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Task</h5>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div class="modal-body">
<p>Task Title</p>
<input type="text" class="form-control" name="" id="textInput" />
<div id="msg"></div>
<br />
<p>Due Date</p>
<input type="date" class="form-control" name="" id="dateInput" />
<br />
<p>Description</p>
<textarea
name=""
class="form-control"
id="textarea"
cols="30"
rows="5"
></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
Close
</button>
<button type="submit" id="add" class="btn btn-primary">Add</button>
</div>
</div>
</div>
</form>
El resultado hasta ahora: 👇
Hemos terminado con la configuración del archivo HTML. Comencemos el CSS.
Agregue estos estilos en el cuerpo para que podamos mantener nuestra aplicación en el centro exacto de la pantalla.
body {
font-family: sans-serif;
margin: 0 50px;
background-color: #e5e5e5;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
Apliquemos estilo al div con la aplicación classname. 👇
.app {
background-color: #fff;
width: 300px;
height: 500px;
border: 5px solid #abcea1;
border-radius: 8px;
padding: 15px;
}
El resultado hasta ahora: 👇
Ahora, diseñemos el botón con el id addNew
. 👇
#addNew {
display: flex;
justify-content: space-between;
align-items: center;
background-color: rgba(171, 206, 161, 0.35);
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
}
.fa-plus {
background-color: #abcea1;
padding: 3px;
border-radius: 3px;
}
El resultado hasta ahora: 👇
Si hace clic en el botón, el modal aparece así: 👇
En el archivo JavaScript, en primer lugar, seleccione todos los selectores del HTML que necesitamos usar. 👇
let form = document.getElementById("form");
let textInput = document.getElementById("textInput");
let dateInput = document.getElementById("dateInput");
let textarea = document.getElementById("textarea");
let msg = document.getElementById("msg");
let tasks = document.getElementById("tasks");
let add = document.getElementById("add");
No podemos permitir que un usuario envíe campos de entrada en blanco. Entonces, necesitamos validar los campos de entrada. 👇
form.addEventListener("submit", (e) => {
e.preventDefault();
formValidation();
});
let formValidation = () => {
if (textInput.value === "") {
console.log("failure");
msg.innerHTML = "Task cannot be blank";
} else {
console.log("success");
msg.innerHTML = "";
}
};
Además, agregue esta línea dentro del CSS:
#msg {
color: red;
}
El resultado hasta ahora: 👇
Como puede ver, la validación está funcionando. El código JavaScript no permite que el usuario envíe campos de entrada en blanco; de lo contrario, verá un mensaje de error.
Independientemente de las entradas que escriba el usuario, debemos recopilarlas y almacenarlas en el almacenamiento local.
Primero, recopilamos los datos de los campos de entrada, usando la función named acceptData
y una matriz llamada data
. Luego los empujamos dentro del almacenamiento local así: 👇
let data = [];
let acceptData = () => {
data.push({
text: textInput.value,
date: dateInput.value,
description: textarea.value,
});
localStorage.setItem("data", JSON.stringify(data));
console.log(data);
};
También tenga en cuenta que esto nunca funcionará a menos que invoque la función acceptData
dentro de la declaración else de la validación del formulario. Síguenos aquí: 👇
let formValidation = () => {
// Other codes are here
else {
// Other codes are here
acceptData();
}
};
Es posible que haya notado que el modal no se cierra automáticamente. Para resolver esto, escribe esta pequeña función dentro de la instrucción else de la validación del formulario: 👇
let formValidation = () => {
// Other codes are here
else {
// Other codes are here
acceptData();
add.setAttribute("data-bs-dismiss", "modal");
add.click();
(() => {
add.setAttribute("data-bs-dismiss", "");
})();
}
};
Si abre las herramientas de desarrollo de Chrome, vaya a la aplicación y abra el almacenamiento local. Puedes ver este resultado: 👇
Para crear una nueva tarea, necesitamos crear una función, usar literales de plantilla para crear los elementos HTML y usar un mapa para insertar los datos recopilados del usuario dentro de la plantilla. Síguenos aquí: 👇
let createTasks = () => {
tasks.innerHTML = "";
data.map((x, y) => {
return (tasks.innerHTML += `
<div id=${y}>
<span class="fw-bold">${x.text}</span>
<span class="small text-secondary">${x.date}</span>
<p>${x.description}</p>
<span class="options">
<i onClick= "editTask(this)" data-bs-toggle="modal" data-bs-target="#form" class="fas fa-edit"></i>
<i onClick ="deleteTask(this);createTasks()" class="fas fa-trash-alt"></i>
</span>
</div>
`);
});
resetForm();
};
También tenga en cuenta que la función nunca se ejecutará a menos que la invoque dentro de la acceptData
función, así: 👇
let acceptData = () => {
// Other codes are here
createTasks();
};
Una vez que hayamos terminado de recopilar y aceptar datos del usuario, debemos borrar los campos de entrada. Para eso creamos una función llamada resetForm
. Síguenos: 👇
let resetForm = () => {
textInput.value = "";
dateInput.value = "";
textarea.value = "";
};
El resultado hasta ahora: 👇
Como puede ver, no hay estilos con la tarjeta. Agreguemos algunos estilos: 👇
#tasks {
display: grid;
grid-template-columns: 1fr;
gap: 14px;
}
#tasks div {
border: 3px solid #abcea1;
background-color: #e2eede;
border-radius: 6px;
padding: 5px;
display: grid;
gap: 4px;
}
Dale estilo a los botones de editar y eliminar con este código: 👇
#tasks div .options {
justify-self: center;
display: flex;
gap: 20px;
}
#tasks div .options i {
cursor: pointer;
}
El resultado hasta ahora: 👇
Mire aquí cuidadosamente, agregué 3 líneas de código dentro de la función.
let deleteTask = (e) => {
e.parentElement.parentElement.remove();
data.splice(e.parentElement.parentElement.id, 1);
localStorage.setItem("data", JSON.stringify(data));
console.log(data);
};
Ahora cree una tarea ficticia e intente eliminarla. El resultado hasta ahora se ve así: 👇
Mire aquí cuidadosamente, agregué 5 líneas de código dentro de la función.
let editTask = (e) => {
let selectedTask = e.parentElement.parentElement;
textInput.value = selectedTask.children[0].innerHTML;
dateInput.value = selectedTask.children[1].innerHTML;
textarea.value = selectedTask.children[2].innerHTML;
deleteTask(e);
};
Ahora, intente crear una tarea ficticia y edítela. El resultado hasta ahora: 👇
Si actualiza la página, notará que todos sus datos han desaparecido. Para resolver ese problema, ejecutamos un IIFE (expresión de función invocada inmediatamente) para recuperar los datos del almacenamiento local. Síguenos: 👇
(() => {
data = JSON.parse(localStorage.getItem("data")) || [];
console.log(data);
createTasks();
})();
Ahora los datos aparecerán incluso si actualiza la página.
Felicitaciones por completar con éxito este tutorial. Ha aprendido a crear una aplicación de lista de tareas mediante operaciones CRUD. Ahora, puede crear su propia aplicación CRUD usando este tutorial.
Aquí está tu medalla por leer hasta el final. ❤️
Fuente: https://www.freecodecamp.org/news/learn-crud-operations-in-javascript-by-building-todo-app/