A sample project
A sample project for this tutorial will be a simple HTML page with two input fields and one button and a simple JS function that summarize number from input fields when button is clicked. The full code is available in the repository.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Frontend CI Tutorial</title>
<script src="js/sum.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div>
<label for="input_number_1">First number:</label>
<input id="input_number_1"><br>
<label for="input_number_2">Second number:</label>
<input id="input_number_2"><br>
<button id="sum_button">Sum</button>
</div>
<div>Result is: <span id="sum_result"></span></div>
</body>
</html>
js/sum.js
const sum = (a, b) => {
return a + b;
};
js/main.js
document.addEventListener('DOMContentLoaded', () => {
const btn = document.querySelector('#sum_button');
const input1 = document.querySelector('#input_number_1');
const input2 = document.querySelector('#input_number_2');
const result = document.querySelector('#sum_result');
btn.addEventListener('click', () => {
const num1 = parseInt(input1.value);
const num2 = parseInt(input2.value);
result.innerHTML = sum(num1, num2);
});
});