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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<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! 😀