Thursday, November 24, 2022
HomeWeb DevelopmentHow one can Construct a TODO App With Vanilla JavaScript (and Native...

How one can Construct a TODO App With Vanilla JavaScript (and Native Storage)


1. Start With the Required Belongings

To make the structure a bit extra distinctive, we’ll use some handmade SVG illustrations and a customized font taken from Envato Components.

SUMMER - FONT PACKSUMMER - FONT PACKSUMMER - FONT PACK
SUMMER – FONT PACK on Envato Components

It’s value noting that the majority of those property will come from a earlier tutorial. In precise reality, we’ll additionally use numerous the positioning methods that we discovered on this tutorial, so it’s value studying it.

How to Build a Responsive Handmade SVG FormHow to Build a Responsive Handmade SVG FormHow to Build a Responsive Handmade SVG Form

2. Proceed With the Web page Markup

We’ll begin with an SVG and a div container:

SVG Sprites

Like we’ve carried out many instances up to now, as an excellent follow, we’ll retailer all SVGs as images in an SVG sprite container. Then, we’ll render them on the display screen every time we’d like by calling the use aspect.

Right here’s the markup for the SVG sprite:

Discover the preserveAspectRatio="none" attribute which we connected to many of the illustrations. We’ve carried out this as a result of, as we’ll see later, our icons will scale and lose their preliminary dimensions.

Container

The container will embrace a type, a div aspect, and an empty ordered checklist:

Inside the shape, we’ll have an enter and a submit button together with their related SVGs:

Discover the title attribute that we’ve added to the enter discipline. Later we’ll use this attribute to entry the enter worth after the shape submission.

Word: In our demo, the autofocus attribute of the textual content discipline gained’t work. In actual fact, it’ll throw the next error which you’ll see in the event you open your browser console:

The cross-origin error due to the autofocus attributeThe cross-origin error due to the autofocus attributeThe cross-origin error due to the autofocus attribute

Nonetheless, in the event you run this app regionally (not as a Codepen venture), this concern gained’t exist. Alternatively, you possibly can set the main target by way of JavaScript.

Contained in the div, we’ll place three nested divs and the related SVG. On this part we’ll maintain monitor of the overall variety of duties (each remaining and accomplished):

Lastly, the objects of the ordered checklist will likely be added dynamically by way of JavaScript. 

3. Outline Some Fundamental Kinds

With the markup prepared, we’ll proceed with some reset types:

4. Set the Important Kinds

Let’s now focus on the principle types of our TODO app.

Container Kinds

The container could have a most width with horizontally centered content material:

Type Kinds

On small screens all type components will likely be stacked:

The form layout on small screensThe form layout on small screensThe form layout on small screens

Nonetheless, on viewports 600 pixels vast and above, the shape structure will change as follows:

The form layout on medium screens and aboveThe form layout on medium screens and aboveThe form layout on medium screens and above

Let’s be aware of two issues:

  • On vast viewports, the enter will likely be twice the scale of the button. 
  • The SVGs will likely be completely positioned components and sit under their adjoining type management. Once more, for a extra detailed clarification, take a look at this earlier tutorial.

Listed below are the types for this part:

Stats Kinds

Subsequent, let’s have a look at the standing bar which can give us a fast report concerning the complete variety of duties.

On small screens it is going to have the next stacked look:

The stats layout on small screensThe stats layout on small screensThe stats layout on small screens

Nonetheless, on viewports 600 pixels vast and above, it ought to change as follows:

The stats layout on medium screens and aboveThe stats layout on medium screens and aboveThe stats layout on medium screens and above

Let’s be aware of two issues:

  • On vast viewports, all baby div components could have equal widths.
  • Equally to the earlier SVGs, this may also be completely positioned and act as a background picture that covers the entire part.

The associated types:

Job Kinds

The duties structure, which we’ll generate dynamically within the upcoming part, will appear to be this:

The tasks layoutThe tasks layoutThe tasks layout

Every activity which will likely be represented by a li could have two elements. 

The markup representation of a taskThe markup representation of a taskThe markup representation of a task

Within the first half, you’ll see a checkbox together with the duty title. Within the second half, you’ll discover a delete button for eradicating the duty.

Listed below are the associated types:

When a activity is incomplete, an empty checkbox will seem. Then again, if a activity is marked as accomplished, a checkmark will seem. Moreover, its title will likely be given 50% opacity in addition to a line by way of it.

Listed below are the types accountable for this conduct:

Lastly, under are the types for the delete button:

5. Add the JavaScript

At this level, we’re able to construct the core performance of our TODO checklist app. Let’s do it!

On Type Submission

Every time a person submits the shape by urgent the Enter key or the Submit button, we’ll do the next issues:

  1. Cease the shape from submitting, thereby stopping a reload of the web page.
  2. Seize the worth which is contained within the enter discipline.
  3. Assuming that the enter discipline isn’t empty, we’ll create a brand new object literal which can characterize the duty. Every activity could have a singular id, a reputation, and be energetic (not accomplished) by default.
  4. Add this activity to the duties array.
  5. Retailer the array in native storage. Native storage solely helps strings, so to do it, now we have to make use of the JSON.stringify() technique to transform the objects contained in the array into strings. 
  6. Name the createTask() perform for visually representing the duty on the display screen.
  7. Clear the shape.
  8. Give focus to the enter discipline.

Right here’s the related code:

Create a Job

The createTask() perform will likely be accountable for creating the duty’s markup.

As an illustration, right here’s the construction for the “Go for a stroll” activity:

The markup structure for a taskThe markup structure for a taskThe markup structure for a task

Two issues are essential right here:

  • If the duty is accomplished, the checkmark will seem.
  • If the duty isn’t accomplished, its span aspect will obtain the contenteditable attribute. This attribute will give us the power to edit/replace its title.

Beneath is the syntax for this perform:

Replace a Job

A activity will be up to date in two alternative ways:

  • By altering its standing from “incomplete” to “accomplished” and vice versa.
  • By modifying its title in case the duty is incomplete. Keep in mind that on this case, the span aspect has the contenteditable attribute.

To maintain monitor of those adjustments, we’ll benefit from the enter occasion. That is a suitable occasion for us as a result of it applies each to enter components and components with contenteditable enabled.

The tough factor is that we can not immediately connect this occasion to the goal components (checkbox, span) as a result of they’re created dynamically and aren’t a part of the DOM on web page load.

Due to the occasion delegation, we’ll connect the enter occasion to the guardian checklist which is a part of the preliminary markup. Then, by way of the goal property of that occasion we’ll examine the weather on which the occasion occurred and name the updateTask() perform:

Contained in the updateTask() perform, we’ll do the next issues:

  1. Seize the duty that must be up to date.
  2. Examine the aspect that triggered the occasion. If the aspect has the contenteditable attribute (i.e. it’s the span aspect), we’ll set the duty’s title equal to the span’s textual content content material.
  3. In any other case (i.e. it’s the checkbox), we’ll toggle the duty’s standing and its checked attribute. Plus, we’ll additionally toggle the contenteditable attribute of the adjoining span.
  4. Replace the worth of the duties key in native storage.
  5. Name the countTasks() perform.

Right here’s the syntax for this perform:

Take away a Job

We will take away a activity by way of the “shut” button. 

Button for removing a taskButton for removing a taskButton for removing a task

Just like the replace operation, we can not immediately connect an occasion to this button as a result of it isn’t within the DOM when the web page hundreds.

Thanks once more to the occasion delegation, we’ll connect a click on occasion to the guardian checklist and carry out the next actions:

  1. Examine if the aspect that’s clicked is the “shut” button or its baby SVG.
  2. If that occurs, we’ll seize the id of the guardian checklist merchandise.
  3. Go this id to the removeTask() perform.

Right here’s the related code:

Contained in the removeTask() perform, we’ll do the next issues:

  1. Take away from the duties array the related activity.
  2. Replace the worth of the duties key in native storage.
  3. Take away the related checklist merchandise.
  4. Name the countTasks() perform.

Right here’s the syntax for this perform:

Depend Duties

As we’ve already mentioned, most of the capabilities above embrace the countTask() perform.

Its job is to observe the duties for adjustments (additions, updates, deletions) and replace the content material of the associated components.

Count tasksCount tasksCount tasks

Right here’s its signature:

Forestall Including New Traces

Every time a person updates the title of a activity, they shouldn’t be capable of create new traces by urgent the Enter key.

Prevent multi linesPrevent multi linesPrevent multi lines

To disable this performance, as soon as once more we’ll benefit from the occasion delegation and fasten the keydown occasion to the checklist, like this:

Word that on this state of affairs solely the span components may set off that occasion, so there’s no have to make an extra examine like this:

Persist Knowledge on Web page Load

To this point, if we shut the browser and navigate to the demo venture, our duties will disappear.

However, wait that isn’t 100% true! Keep in mind that every time we do a activity manipulation, we additionally retailer the duties array in native storage. For instance, in Chrome, to see the native storage keys and values, click on the Utility tab then, increase the Native Storage menu and eventually click on a site to view its key-value pairs.

In my case, listed below are the values for the duties key:

An example with local storageAn example with local storageAn example with local storage

So, to show these duties, we first have to retrieve them from native storage. To do that, we’ll use the JSON.parse() technique which can convert the strings again to JavaScript objects. 

Subsequent, we’ll retailer all duties within the acquainted duties array. Understand that if there’s no information in native storage (as an illustration the very first time we go to the app), this array is empty. Then, now we have to iterate by way of the array, and for every activity, name the createTask() perform. And, that’s all!

The corresponding code snippet:

Conclusion

Phew! Thanks for following alongside on this lengthy journey people. Hopefully, you gained some new information right this moment which you’ll be capable to apply to your individual initiatives.

Let’s remind ourselves what we constructed:

For sure, constructing such an app with a JavaScript framework is perhaps extra secure, simple, and environment friendly (repainting the DOM is pricey). Nonetheless, figuring out to unravel this sort of train with plain JavaScript will enable you to get a strong grasp on its fundamentals and make you a greater JavaScript developer.

Earlier than closing, let me suggest two concepts for extending this train:

  • Use the HTML Drag and Drop API or a JavaScript library like Sortable.js for reordering the duties.
  • Retailer information (duties) within the cloud as a substitute of the browser. For instance, exchange native storage with a real-time database like Firebase.

As all the time, thanks quite a bit for studying!

Extra Vanilla JavaScript Apps

If you wish to need to study constructing small apps with plain JavaScript, try the next tutorials:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments