Posts

Showing posts from February, 2022

You Can Still Type Non-Numbers In A Type Number HTML Input

We can set the type property of an HTML input to number to accept only numbers. But we can still type in something like 00001213400012 or 1-5-5-5--442-, which are not quite what I usually define as normal numbers. By the way, I wrote that input values are treated as type string even if the type of the input is set to be number. Try type in 000123 or 1-2-53 in this input which is set to be type number. Type: Input: Using Number or parseFolat We can use parseFloat() or Number() method to convert the type of input values from string to number, now try to type in 000123 or 1-2-352. Type: Input: <input oninput="show(this)" type="number" /><br /> <div>Type: <span id="showType"></span></div> <div>Input: <span id="showNo"></span></div> <script> function show(t){ var value = Number(t.value);//or parseFloat(t.value); showType.innerHTML = typeof(value); showNo...

HTML Input Max or Min Property Will Not Work If Users Type In Directly Into the Input Box

We can defince max or min property for input with type of number or date. The max or min property will limit the range of input value when users click on the arrow on the right side of the input. But the max or min propety won't work if users manually type in the inputs. Try use the arrow and type in the below input to see result. <input oninput = "showValue_1.innerHTML = this.value" type = "number" max =5 min = 0> <div id = "showValue_1"></div> Solution We can use some JavaScript to set the max or min value of an input. <input max="5" oninput="getValue(this)" type="number" /> <div id="showValue_2"></div> <script> function getValue(t){ Remove 0 before any number. //t.value = Number(t.value); var value = t.value var max = t.max; var min = t.min; //Add a Number method to value in the if statement, becaues value may be treated as a string. if(Number(...

How to Make A Time Controlled Loop in JavaScript

Image
For loops are used all the time in software development. But for loops do not have the time controlled mechanism. We have to build it from scratch. Suppose we want to show elements in an array. Without time control effect, it will just print everything out at once. Print <button onclick = "showNumberFunc()">Print</button> <div id = "showNumbers"></div> <script> var arr = [1,2,3,4,5,6,7,8,9]; function showNumberFunc(){ showNumbers.innerHTML = ""; for(let i = 0;i < arr.length; i++){ showNumbers.innerHTML += arr[i]; }; }; </script> Print <button onclick="showNumberFunc_timeControlled()">Print</button> <div id="showNumbers_timeControlled"></div> <script> var arr = [1,2,3,4,5,6,7,8,9]; var i; var myInterval; function print(){ showNumbers_timeControlled.innerHTML += arr[i]; i++; if(i == arr.length){ clearIn...

JavaScript Arrow Function Inherits the Parent Scope for "This"

"This" is confusing in JavaScript. It refers to some object. But when "this" refers to an unintended object, our code will act unexpectedly. This happens during the construction of an object, when we want to refer to the own object in its methods. For example, var name = "global name" var obj_1 = { name:'obj name', call:function(){ console.log(this.name); } }; var obj_2 = { name:'obj name', call:() => { console.log(this.name); } }; obj_1.call(); //obj name obj_2.call(); //global name Here, in obj_1, the method defined by the regular function refers to the own object with "this", whhile the method defined by the arrow function refers to the window object in obj_2 During Object Construction "this" Still Points to The Global Scope However Deep in the Object Structure With Arrow Functions. Unlike regular function, when an object is constructed, all methods in the object will point "this...

"This" Problem Solved for Fring Object Method with SetInterval or AddeventListener

 Lets talk about the problem with addEventlistener to a button. Consider the following code. <button id = "call">Call</button> <script> var name = "global name"; var obj = { name:"obj name", call:function(){ alert(this.name); } }; obj.call(); // obj name call.addEventListener("click",obj.call) // when the button is clicked, windows alerts nothing. </script> The problem is we want to be able to refer to "obj name" when click on the button Next Problem is with setInterval <script> var name = "global name"; var obj = { name:"obj name", call:function(){ console.log(this.name); }, run:function(){ setInterval(this.call,200) } }; obj.run(); // global name </script> The problem is we want to show "obj name" on the console every 1 fifth of a second. The above two examples are not workingm, neigher console.log nor alert refer to the obj and 'this' refers...

How to Copy An Array of Arrays in JavaScript

When we want to grab data from an array, we may accidantally change the value in the original array. Then, when we can't access the original array. This is problematic. For Example var arrOriginal = [1,2]; var arrCopy = arrOriginal; arrCopy[0] = 10; console.log(arrOriginal); // shows [10,2] The original array is modified by modifying a supposedly different array. This can also happen with array pop, splice and shift. One way to solve this problem is to use array.push method to assign values to the new arrray.   var arrOriginal = [1,2,3]; var arrCopy = []; arrCopy.push(arrOriginal[0]); arrCopy.push(arrOriginal[1]); arrCopy.push(arrOriginal[2]); arrCopy[0] = 10 console.log(arrOriginal); // shows [1,2,3] Or, we can use the spread operator. var arrOriginal = [1,2,3]; var arrCopy = [...arrOriginal]; arrCopy[0] = 10; console.log(arrOriginal); //shows [1,2,3] console.log(arrCopy); //shows [10,2,3] Now, here is the problem! When copy an array using eighter the push me...

Get Mean and Standard Deviation from an Array of Numbers Using Vanilla JavaScript

One way to get the mean and the standard deviation from an array of numbers is to use math.js. <script src = "https://cdnjs.cloudflare.com/ajax/libs/mathjs/10.1.1/math.js"></script> <script> var arr = [1,2,3]; console.log(math.mean(arr)); // returns 2 console.log(math.std(arr)); // returns 1 </script> What if we don't want to use any third party libraries. We can build our own mean or standard deviation calculation function using vanilla JavaScript. Mean function getMean(array){ var total = 0; array.forEach(x=>{ total += x; }); return total/array.length; }; Standard Deviation Unbiased function getStd(array){ var total = 0; var l = array.length; array.forEach(x=>{ total += x; }); var mean = total/l; var squareErrors = 0.; array.forEach(x=>{ squareErrors += Math.pow(x-mean,2); }); return Math.sqrt(squareErrors/(l-1)); }; Standard Deviation Biased function getStdBiased(array){ var total = ...

Convert Stock Prices Into Returns in JavaScript

The following Javascript code is for converting an array of stock price into an array of returns. The length of the array of returns will have a length that is 1 unit smaller than the one of prices. This is because we need 2 prices for a return. The code is following: function getReturn(array){ var returnarray = []; var l = array.length; for(let i = 0; i < l-1; i++){ returnarray.push(array[i+1]/array[i]-1) } return returnarray; }; Type in the textarea of some numbers seperated by commas. 100,101,102 Get Returns Prices: 100,101,102 Return: We can also get the mean return and return standard deviation, too. function getReturnObj(array){ var objecttoreturn = {}; var returnarray = []; var l = array.length; for(let i = 0; i < l-1; i++){ returnarray.push(array[i+1]/array[i]-1) }; var mean = returnarray.reduce((a,b,c,d)=>{ if(c==d.length-1){ return (a+b)/d.length } return...

How to Make Inputs Only Accpet Integer Numbers

How to make inputs accept only integers. One way is to set the increment to 1 and type to number like this one: <input type = "number" step = "1"> But this has some flaws although users can only change the input number by 1 each time they hit the up or donw arrow on the right of the input, they can actually manually type in some number that is not an integer such as 1.5. Solution Now with a little JavaScript code, we can make an input strictly accept integers <input oninput = "this.value = parseInt(this.value)" type = "number"> <input oninput = "this.value = Math.floor(this.value)" type = "number"> <input oninput = "this.value = Math.ceil(this.value)" type = "number"> Now, users can't type in non integer values Accepting Only Positive Integers. What about accepting only positive integers? Try the following. <input oninput="this.value = this.value <= ...

Computational Pressure can be Reduced by Applying Math for Simulating Stock Price

Computers now are much faster than 10 years before. But, with a little bit of some math problems, new computers still have to work very hard. I recently built a tool that models stock price movement, SPY ETF to be precise with the following steps: I first obtained the stock daily closing price adjusted for dividend payout from Yahoo Finance scv file, then converted to daily returns. With an array of SPY daily returns, I calculated the mean and standard deviation. Finally I could model SPY price movement based on the geometric Brownaian motion that stock price may follow. The model app is here , feel free to try. Here is the problem After building the above mentinoed modeling tool, I went ahead and built another tool that can model if we would spend all our retirement money if we sell 4%, each year, of our SPY-only portfolio. I thought, instead of grabing yearly closing prices of SPY from Yahoo Finance again, I could just use the daily returns for modeling. Now, the problem is, the assu...

How to Create Hamburger Menu Icon Without Thrid Party Code

When making a responsive menu, we sometimes need to use a hamburger menu icon to toggle opening and closing for the menu list.  We can use font-awesome to get the icon. If you don't want to use any third party library like font-awesome to display a hamburger menu bar, you can use the in-built HTML characters like the following: Symbol Code ☰ &#9776; &#x2630; ⚌ &#9868; &#x268C; = &#61; &#x3D; ≡ &#8801; &#x2261; &equiv; &Congruent; Ξ &#926; &#x39E; &Xi; ≣ &#8803; &#x2263; How to Use Just type in the code in HTML file. &#9776; <!-- It will display ☰ --/>

How to Toggle between Hiding and Showing for HTML Elements

The basic mechnism for hiding and showing HTML elements are the CSS properties: display and visibility. When we want to hide we set the element style's display to none or visibility to hidden. What if we want to contorl when a HTML element is showing and hiding? We must write some JavaScript code like this: <button onclick = "hide()">Hide</button> <button onclick = "show()">Show</button> <div style = "background-color:lightgrey" id = "sometexttotoggle">some text</div> <script> function hide(){ document.getElementById('sometexttotoggle').style.display = "none"; } function show(){ document.getElementById('sometexttotoggle').style.display = "block"; } </script> Hide Show some text Or this one with visibility <button onclick = "hide()">Hide</button> <button onclick = "show()">Show</button> ...

HTML Elements with Position Fixed will Inherit the Top and Left Property from Parents

HTML elements when set to position: fixed without defining the top or left CSS property will automatically inherit from their parents. For Example Click the button bellow to see a div inside a div to see the inner div inherit the parent div automatically. Click to Show <div style = "background-color: grey; height: 70%; left: 25%; position: fixed; top: 25%; width: 70%"> <div style = "background-color:black;position:fixed;width:50%;height:50%"></div> </div> This can cause problem if you are makeing a sticking nav bar, menu, or modal. You need to adjuct the inner div's top or left CSS property to put where you want it to be. Now try this new button Click to Show left: right: bottom: <div style = "background-color: grey; height: 70%; left: 25%; position: fixed; top: 25%; width: 70%"> <div style = "background-color:black;position:fixed;width:100%;height:100%; left:0 "></div> </div> ...

How to Add Amazon Associate Custom Popover Ads

 Amazon associate provides mobile popover ads. But, what if we want to add a desktop version. Show Ad Sample Code <button onclick = "myCustomAzAd.style.visibility = 'visible'">Show Ad</button> <div id="myCustomAzAd" style="background-color: grey; border: 1px solid; bottom: 1px; height: 100%; position: fixed; width: 100%; z-index: 9999;"> <span class="hideAd" onclick="myCustomAzAd.style.visibility = 'hidden';">X</span> //Amazon Ad code here <div id="amzn-assoc-ad-xxxfdexx-3xxx-4xxxx-bxxx-axfxxxxxxbb"></div> <script async="" src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&amp;adInstanceId=00xxxxxx-3xef-xxxxe-xxxx-xxxxxxxx"> </script> </div> X You can also set the ad to apear every some period. Show ad every 10 seconds <div id="myCustomAzAd" style="opacity:0.95;top:0;lef...

How to Make a Resume Interval Function in JavaScript

When we create time interval, the interval is assigned with an id, and when we clear it we need to clear it with its id (detail explained in this article ). This is why examples in this post all pre-clear interval before creating it in order to avoid duplicating intervals. Now, what if we want to resume the interval which we have already cleared? There is no native resume interval method, we need to build one for ourselves. Cosider the following code: Start Stop Resume 0 <button onclick = "startcount()">Start</button> <button onclick = "stopcount()">Stop</button> <button onclick = "resumecount()">Resume</button> <div id = "showcount">0</div> <script> var count; var interval; function counting(){ showcount.innerHTML = count++; }; function startcount(){ count = 0; clearInterval(interval); interval = setInterval(counting,250); }; functio...

How to Avoid Creating Multiple Intervals with JavaScript

When we wanat to create an app that is time controlled we may accidentally create multiple time intervals that can cause some problems. Consider this counter button.The more you click the faster it adds the counts. This is due to extra interval you create every time you click the button 0 <button onclick = "setInterval(()=>{this.innerHTML++},500)">0</button> A simple solution is to clear the interval even before you create it. 0 <button onclick = "counting(this)">0</button> <script> var myInterval; function counting(b){ clearInterval(myInterval); myInterval = setInterval(()=>{b.innerHTML++},500) } </script> Here my "myInterval" variable has to be set as a global variable otherwise, the interval won't be cleared. <button onclick = "counting(this)">0</button> <script> function counting(b){ var myInterval; clearInterval(myInterval); myInterval = ...