I want to build…

by leonardossmoke

I want to build the core of my habit app, and dip a bit into HTML and javascript.

The core of the program is a single page that asks a single question: “Have you done your habit today?” If the user answers yes, the page changes to “Good work!”

Let’s implement this with just HTML and javascript.

When developing, I like to ask myself, “What is the simplest, dumbest thing I can do to get started? First, let’s build the simplest page possible.  I need to display the question and a button called “Yes” for the user to press.
<html>
<head>
</head>
<body>
<p>
Have you done your habit today?
</p>
<button> yes </button>
</body>
</html>

Right now, the code is not very interactive. When we click the button, we want the text of the question to change to “Good Work!”  Let’s add a little inline javascript.

<button onclick=”document.getElementById(‘question’).innerHTML=’Good Work’;” >

And voila!  We have a webpage that, when you click on a button, it changes the text in a box.  This is the simplest, dumbest thing I could do to get my project off the ground.

The reason I like this function is that it’s relatively readable.  Let’s walk through what this function step by step.

onclick = “document.getElementById(‘question’).innerHTML = ‘Good Work’;”

What does this function do?  It changes the text on the webpage to say Good work when you click on the button.  How does it do it?

When I read code, this is how I read that particular line.  “When the button is clicked, go to the webpage (which is named Document), find the element on it with an ID named question, get the text out of it, and replace it with ‘Good Work.’

For Javascript novices, even this function is a bit overwhelming.  More experienced Javascript coders will look at it and say “Eww, inline Javascript.”  How awful!

Yes, yes.  I said it was the simplest, dumbest thing I could write.

This is nearly the simplest, dumbest HTML page and program you can write in JavaScript.  It is also bad practice.  Next post we shall refactor it.