JavaScript – A function, calling a function! :)
Hallo Leute! 🙂
Today I was putting some more efforts in JavaScript, and I think I have finally realized how the how the trick with a function calling a function is actually done.
Now, lets imagine the following easy scenario for an app – we have an input box and a button, whenever we click the button, the value from the input box is added to our total. As easy as this:
You may see that I have started with 5, then 100, 500, 850 to get the value of 1455 all together. Not a great IT achievement, but the trick is that I have used a function calling a function for this.
At the start of the program, I have defined the variable countMe = makeCounter(); Thus, this countMe(), was associated with the onClick event of the button “O Yeah!”, and pretty much it worked! 🙂
Thank you for your interest, here comes the code:
<html>
<head>
<title>Count Me</title>
<style>
body, button {margin:15px;}
div {padding:10px; background-color: yellow }
</style>
<script>
window.onload = function()
{
var countMe = makeCounter();
div = document.getElementById("message");
myButton = document.getElementById("clickMe");
myButton.onclick = function ()
{
div.innerHTML += countMe() +"|" + parseInt(document.getElementById("myNumber").value, 10) + "<hr>" ;
}
function makeCounter()
{
initial = 0;
function counter()
{
var number = parseInt(document.getElementById("myNumber").value, 10);
initial += number;
return initial;
}
return counter;
}
}
</script>
</head>
<body>
<button id = "clickMe">O Yeah!</button>
<input type="text" id = "myNumber"/>
<div id="message"></div>
</body>
</html>
Enjoy it! 😀