Creating a Simple Calculator with HTML and JavaScript
Simple Calculator
Objective: Implement a simple calculator that can perform basic arithmetic operations like addition, subtraction, multiplication, and division.
Introduction:
In today’s tutorial, we’re going to dive into the basics of web development by creating a simple calculator. This project is perfect for beginners and those looking to refresh their coding skills. We’ll be using HTML for the structure and JavaScript for the functionality.
HTML Structure:
Our HTML is straightforward. We start with a tag containing a
with the class “main”. Inside, we have two input fields for our numbers, a select dropdown for our operations (add, subtract, multiply, divide), a button to calculate the result, and a paragraph element to display the result.
<main>
<div class="main">
<input type="text" id="todoInput">
<button id="addTodoBtn">Add To-Do</button>
<ul id="todoList"></ul>
</div>
</main>
+ – * / Calculate
JavaScript Logic:
Our JavaScript starts by selecting all necessary elements from our HTML. We add an event listener to our calculate button so that when it’s clicked, a function is executed. This function retrieves the values from our input fields, checks if they are numbers, and then performs the operation based on the selected option. The result is then displayed in our paragraph tag.
const btn = document.getElementById('addTodoBtn');
const inputValue = document.getElementById('todoInput');
const ul = document.getElementById('todoList');
btn.addEventListener('click', () => {
if (inputValue.value != '') {
const li = document.createElement('li');
li.textContent = inputValue.value;
li.addEventListener('click', function() {
this.parentNode.removeChild(this);
});
ul.appendChild(li);
inputValue.value = '';
}
});
Conclusion:
Creating a simple calculator is a great way to start learning HTML and JavaScript. It helps you understand how to structure a webpage and how to manipulate data using JavaScript. Remember, the key to learning programming is practice, so don’t hesitate to modify this code and experiment with it on your own. Happy coding!
Remember: Always test your calculator thoroughly to ensure all operations work correctly. Feel free to expand on this project by adding more functionalities or improving the UI/UX design.