Building a web-based app

You are here: Home » MiltonMarketing Blog » Computer Programming Languages » Web App » To-do-list app » Building a web-based app

Building a web-based app

Making buttons run code

We now need to make the button in our app interactive. To make the button run JavaScript code when we click it, we need to add the onclick attribute to our button < input/ > tag, like we did earlier.

When the user clicks on the button, we want it to call a JavaScript function. All we have to do is set the value of our onclick attribute to the name of the function we want to call.

Let’s code a button that will call a function that pops up an alert when it’s clicked. First, create the JavaScript function you need. Then add the onclick attribute to the < input/ > tag for the button.

Finally set the value of the onclick attribute to the name of the function. Do this by using the equals sign (=) and double quotes (” “). The code we need looks like this:

<!DOCTYPE html>
<html>
<head>
 <title>To-Do List App</title>
 <script>
 function addItem() {
 alert("Remember dog biscuits!");
 }
 </script>
</head>
<body>
 <p>Special Exhibition To-Do List</p>
 <br/>
 <input type="text" value="Type here to add task"/>
 <br/>
 <input type="button" value="Add item" onclick="addItem();"/>
 <br/>
</body>
</html>

Now when you click on the button, the onclick attribute calls the JavaScript function and an alert pops up.

Now practise using the onclick attribute to make a button that pops up an alert.

1) Open up your text-editing program. Create a new HTML file called button.html. Then copy and paste your code from app.html into your new file. In your < body > add an onclick attribute that calls a JavaScript function to your button, like this:

<!DOCTYPE html>
<html>
<head>
 <title>To-Do List App</title>
</head>
<body>
 <p>Hello World! To-Do List App</p>
 <br/>
<input type="text" value="Type here to add task"/>
 <br/>
 <input type="button" value="Add item" onclick="addItem();"/>
 <br/>
</body>
</html>

2) Add the < script > tag to your < head >. Create a JavaScript function that will pop up an alert when it’s called. Your code will look like this:

<head>
 <title>To-Do List App</title>
 <script>
 function addItem() {
 alert("Pick up milk!");
 }
 </script>
 </head>

3) Save your HTML file and open it in your browser. Your button will now pop up an alert when you click on it.

About the Author:

I am a loving father, & husband. I am a computer enthusiast. I have used and enjoyed computers since I was young and I enjoy teaching young minds how to code, because it teaches them how to think. Today with YouTube, and social media garbage our youth are losing the ability to think on their own and solve problems. I believe this is a serious epidemic as kids today dont understand that technology is a tool. This tool is being abused, and its underlying effects are taking its toll on kids behaviour, and learning.