Posts

Showing posts from January, 2022

How to Add Text in An Image

Image
Sometimes we want to add text in the image, not below or above it. We can set the position, top, right, bottom, or left property or the text element.  One important thing to keep in mind is that the we nee to add a some element to wrap around the target image and the text element we want to show in the image. Example and Code top-left: top: top-right: left: bottom-right: bottom: bottom-left: right: Apples <div style = "posotion:relative">      <img src = "something.jpg">      <div style = "position:absolute; bottom:0;left:45% ">some text</div> </div> How to Use Make sure the img tag and text div tag are wrap in a div tag. The wraper tag needs to have position: relative property, so that the text div can sit in it. Set the text div to position: absolute; and start defining the postion, left, top, right, or bottom until the text is at where you want it to be. One trick is to remember t...

Plotly.js is Easier Than Chart.js in Dynamically Rendering Charts

In this article , we provide a couple ways to update ot redraw the chrats when using Chart.js. Unfortunatly, it is a lot of work to do redraw chrats with Chart.js. Plotly.js is much easier. With Plotly.js, all you need to do is to recall the function, and it works, unlike chart.js causing an error by recalling new Chart. The Plotly.newPlot() method would just grab the div with a certain id and clear the div, and draw on it. So every time Plotly.newPlot() is called, w a new chart is drawn. Plotly.newPlot(); Playgound Draw Playground Code <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <button onclick="draw()">Draw</button> <div id="myPlot" style="max-width: 700px; width: 100%;"></div> <script> function draw(){ var xArray = []; var yArray = []; var i = 0; setInterval(()=>{ xArray.push(i++); yArray.push(Math.random()*10); var data = [{ x: xArray, y: y...

How to Randomly Arrange a JavaScript Array

Here is a way to randomly arrange an array in JS. The logic is we randomly select an element from the original array and put it in the first element of a new array. Then, randomly choose another element from the original array and put in the second element of a new array. We continue unitl we have selected all elements from the origial array. The new array is a randomly ordered array from another array. A funtion to generate a randomly ordered array. function getrandomorderedarray(a){ var newarray = []; var inputarray = [...a]; var l = inputarray.length; for(let i = 0; i < l; i++){ var xxx = inputarray.splice(Math.floor(Math.random()*(l-i)),1); newarray.push(xxx[0]); } return newarray; }; Playground get new randomly ordered array 1,2,3,4,5,6,7,8,9,10 We can also create an array of arrays of a same random order if the arrays are of the same length. function getRandomOrderedArrayOfArrays(a){ var newarray = []; var inputarray = []; var l = a[...

How to Disable and Enable HTML Inputs, Buttons or Textareas

Image
 HTML inputs, buttons and textareas have the "disanled" attributes. if you want to set them to be disabled, you can put the "disabled" attribute in the html tags such as  <button disabled>button</button> <input disabled> <textarea disabled>></textarea> button > What if we want to disable the above elements? We can use the following code. <button id = "demobutton">button</button> <button onclick="demobutton.disabled = false">enable button</button> <script>     demobutton.disabled = true; </script> button enable button Interesting Facts You can use somebutton.setAttribute("disabled","true"), but you can't use somebutton.setAttribute("disabled","false"), because the 'disabled' attribute is not defined by disabeld = "true" or "false".  If the "disabled" attribute is there, it w...

Is a 17.3 Inch Monitor Big Enough for Programmers?

Image
Is a 17.3 Inch Monitor Big Enough for Programmers? Yes or no, it depends. When I am coding, I want to be able to see the app or website that I am developing on the screen. This means my general setup is code editor on the left, the app or website result on the right, and the console or terminal on the bottom. Below is the screenshot of my 17.3 inch monitor laptop. I can display 24 lines of code on the working panel, console on the bottom while checking any changes on my work on the right. But I sometimes want to be able to display 2 code files when working, which can not be done with a 17.3 inch monitor.

Connecting <input> with "this" or "event"

When our web app or website has inputs, sometimgs we want to pass the input value to some JavaScript functions to process. The intuitive way is to give an id to the input and then use document.getElementById("thatinputid").value to access to the value. But, there are other ways that may help you write way simpler code, and even help you bind logics together.. Using "this" The following input and result have this code: <input oninput = "showinputvalue_1.innerHTML = this.value"> <div id = "showinputvalue_1"></div> Where the div tag with the id "showinputvalue_2" has its innerHTML bounded with the input's value by using this.value Using "event" The following input and result have this code: <input oninput = "showinputvalue_2.innerHTML = event.target.value"> <div id = "showinputvalue_2"></div> Where the div tag with the id "showinputvalue_1" has its i...

InnerHTML and innerText Usages

 innerHTML is use to declare some element's inner HTML and innerText The folowing playgronund shows the difference. Try type in some html code,such as h1, h2, or button tags to see effects. hi innerHTML example hi innerText example <h2>hi</h2> Plauground Source Code <textarea oninput="showhtml.innerHTML = this.value;showtext.innerText = this.value;"><h2>hi</h2></textarea> <h3>innerHTML example</h3> <div id="showhtml"><h2>hi</h2></div> <h3>innerText example</h3> <div id="showtext">&lt;h2&gt;hi&lt;/h2&gt;</div> The idea is when you want to output html tags as the wording in the browser, use innerText. If you want to output the html elements, use innerHTML The other thing is innerHTML and innerText show opposite results have you grab what is inside the tags. What I mean is when you want to output html in text, you use innerText, but whe...

Binomial Distribution with Vanilla JavaScript

 JavaScript has a built-in Math.random method what gives a uniform random variable between 0 to 1(exclusive) Suggested Reading: Does JavaScript's Math.random() method Create Uniform Random Variables? Application of the Central Limit Theorem: Modeling Normal Distribution Using JavaScript What if we want to model a binomail distribution? It's simple. We just need to set a threshhold of 0.5 that a random uniform variable is smaller that 0.5, it is 0 and, otherwise 1. Playground Probability of getting 1: Get Binomial Random Variable Sample Code var pp = 0.5; var results = []; function flip(){ results.push(Math.random()<pp?1:0); var total = 0; var totalsquareerror = 0 results.forEach(x=>{ total+=x; }); var mean = total/results.length; results.forEach(x=>{ totalsquareerror += (x-mn)**2; }); }; If you want a random coin flip resutle, you can use the following c...

Linear Regression with Vanilla JavaScript

Machine learning is not a programming language. It's more about math. Programming languages are the tools.  Linear regression in machine learnning is the proceess to find the corresponding slope and y intercept. With the fundamental knowledege of some calculus one can code up some algorithm for linear regression with any programming language. We want to find the parameters for x and y intercept with y =ax + b, where we set a =1 and b = 0. After every training cycle a and b will change until they fit the data most accuretly. Playgroud Add data: x: y: Add Data x y Start Learning Stop Learning Learning Rate: Training Speed: times per second. Line Formula: y = x Mean Standard Error: //define line function f = a*x + b var a = 1; var b = 0; //define training function function training(){ //lg stands for loss gradient or slope how far away it is from the best parameter. //lga is the loss gradient for parameter a. //lgb is the loss ...

How to Dynamically Add SVG Elements Without Using CreateElementNS

When woking with data visuallization on the web, we need to add data points dynamically. Then, in orde to add data points, we need to create svg elemets such as <circle>. We can't just use document.createElement(''circle") and append child to the parent svg. It just won;t work. We need to use document.createElementNS(""http://www.w3.org/2000/svg"","circle"); <svg id="mySvg1"> </svg><script> var myPoint1 = document.createElementNS("http://www.w3.org/2000/svg","circle"); myPoint1.setAttribute("cx","50"); myPoint1.setAttribute("cy","50"); myPoint1.setAttribute("stroke","black"); myPoint1.setAttribute("r","20"); mySvg1.appendChild(myPoint1); </script> What If I Don't Want to Usr the Weird Look CreateElementNS Code? Yes, you can add svg element without using createEleme...

Working with HTML Textarea Tag

HTML textarea tag allows us to put a big box where users can type in text or even some code. There are quite a few things we need to pay attention to when working with <textarea></textarea>. The size of textarea tag is not defined bt style, but by "rows" and "cols" attributes. Rows dictates the height while cols dictates the width, though, the textarea is drag-expandable. The value attribure is not renderd on the webpage, but its innerHTML is. When typing in the textarea, its value changes but not its innerHTML. The value of textareas is treated as string, when thers is a linebreak, there will be a "\n" hidden in the string. Try Type in this textarea. 123 Value: InnerHTML: <textarea oninput="showvalue.innerHTML = this.value;showinnerHTML.innerHTML = this.innerHTML;" value="abc">123</textarea> <div>Value: <span id="showvalue"></span...

Working with CSV FIle from Yahoo FInance Asset Data

When working with data, one issue is with the csv file. I don't know why people don't just provide json file which is much easier to work with. Here is an example csv file pulled from Yahoo Finance,

Build Reusable Components with Native JavaScript Code

One benefit of using some JS libraies such as Vue or React is that they provide ways to building reusalble components. Here, I try to build reusalble components using natvie JS to see if can grasp the logic behind them. I use class like React. <span id = " button1 "></span> <span id = " button2 "></span> <span id = " button3 "></span> <script> function Counter(id){     this.el = document.getElementById(id);     this.count = 0;      this.add = function(){        this.count++;        this.el.innerHTML = `<button onclick = "${id}.add()">${this.count}</button>`;       }     this.el.innerHTML = `<button onclick = "${id}.add()">${this.count}</button>`; } var button1 = new Counter('button1'); var button2 = new Counter('button2'); var button3 = new Counter('button3'); </script...

Working with Native HTML Date Selector: <input type = "date">

If you are looking for a in-built date selection box, there is one that is native to html. It comes with html input tag. Just assign "date" to its type attribute, you are good to go. One a date is selected on the input with type, date, its value is a string of the format "xxxx-xx-xx", year-month-day.  It's a string, so  if you want to play around with the date, you new to create a date object using the date string you get from the input value. <input id="dateselector" oninput="getdate()" type="date" /> <script> function getdate(){ var date = document.getElementById('dateselector').value; var newdate = new Date(date); document.getElementById('showdate').innerHTML = date; } </script> <input id="dateselector" oninput="getdate()" type="date" /> <script> function getdate(){ var date = document.getElementById('dateselector...

Make Reactive DOM Elements With Just Native JavaScript

For a while have I wondered how some JS libraies, such as Vue or React make DOM reactive. And by the way, tha DOM being reactive to data change is probably one of the reasons why Vue or React has become famous in the first place. How does Vue or React make DOM reactice to data change? I don't know. Though, I have tried to read their source code, but failed to understand the mechanism. So I tried to make my own DOM reactive system. Playground + + Sample Code <div> <span data-data="message1"></span> <span data-data="message1"></span> <button onclick="addfunc1()">+</button><br> <span data-data="message2"></span> <span data-data="message2"></span> <button onclick="addfunc2()">+</button> </div> <script> var data = { message1:0, message2:0 }; //Define dat...

Make a Todo App with Native JavaScript

Many people share how to make a todo app using JavaScript library like Vue or React. I think by making one with just pure native JavaScript, I can train myself with project structuring. Add <div> <input id ="todoinput"> <button onclick = "add()">Add</button> </div> <ol id = "todos"></ol> <script> var i = 1; function add(){ var newtodo = document.createElement('li'); newtodo.setAttribute("id","todo" + i); newtodo.innerHTML = `${todoinput.value}<button onclick = "deletefunc(${i})">Delete</button><button onclick = "updatefunc(${i})">Update</button>`; todos.appendChild(newtodo); todoinput.value = ""; i++; }; function deletefunc(n){ todos.removeChild(document.getElementById("todo" + n)); } function updatefunc(n){ document.getElementById("todo" + n)...

JavaScript Trick: Simplest and Shortest Code for Hiding and Displaying as to Make Accordions

Image
There are many ways to hide and show content on a website, one of the simplest ways is to use inline event handlers, combined with ternary operators. This method creates resuable accordion component using native code, which can be used in blogging content management system like this blog, Blogge,or WordPress. Just use the sample code below. Example topic 1 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eu tristique libero. Pellentesque aliquam libero eget tempor ultricies. Etiam fringilla tincidunt commodo. Aenean consectetur porta nisi ac rutrum. Nullam aliquam fringilla lacus, nec cursus sapien pulvinar nec. Aenean nec nisi quis lectus laoreet pretium at id odio. Praesent vehicula maximus justo in semper. Morbi mattis sollicitudin turpis, eget condimentum purus rutrum a. Pellentesque at ligula in ex volutpat scelerisque sed vitae sem. Aliquam tincidunt gravida tellus eu porta. Proin aliquet risus et lectus varius tempus. ...

How to Add Labels to the X,Y Axes with Chart.js

Image
Chart.js helps add charts on the web easily, and steps to add labels to the X,Y axes with Chart.js are as follows: Find Chart object. Find "options" inside the Chart object. Locate or add "scales" inside "options". Then add labels to the X,Y axes. Code Sample <div> <canvas id="myChart"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> const labels = [ '1', '2', '3', '4', '5', '6', ]; const data = { labels: labels, datasets: [{ label: 'Data', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: [0, 10, 5, 2, 20, 30, 45], }] }; const config = { type: 'line', data, options: { scales:{ x:{ title:{ display:true, tex...

Make CSS Tab Menu Without JavaScript

 To improve user experience on the web, sometimes it is useful to add some functionalities such as menu, and one type of menu is the "tab menu".  Tab menu is used in a way that it sorts content, and when the topic tab is click, content under that topic is shown. An example is below: tab 1 tab 2 tab 3 Content to tab 1 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed elit arcu, tincidunt at elit sed, efficitur sagittis mauris. Pellentesque vulputate neque non quam posuere fermentum. Content to tab 2 Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed maximus ex ex, eu porttitor arcu pretium eget. Nulla sed elementum nunc.  Content to tab 3 Sed vulputate odio a bibendum pellentesque. Nullam purus sem, accumsan vitae efficitur nec, fermentum non metus. Problem The problem is whenever we click a tab, the window will jump down if there is more content than the window can hold, and when this happens, we w...

Do We Still Need to Use document.getElementById Anymore

One of the notorious lines of code is the "document.getElementById" in JavaScript. because this line will appear again and again, and even with copy and paste, you still need a declare a DOM element and change the element id. This is a lot of work. I guess this is one reason why jQuery has been famous for. You just need to write var xyz = $(#someid) which is fairly short. But now with most browsers support ES7 now and one new feature is that we no longer need to declare the element anymore. We can just call the element in JavaScript by its id. Playground Sample Code The above app has the following code: <input id = "input20220107"> <div id = "app"> </div> <script> input20220107.addEventListener("input", () => app.innerHTML = input20220107.value); </script> The automatic call for the document.getElementById feature also works for inline JavaScript like this one, Type in the input box below. ...

Vue Components Need to be Registered Before Use

Vue.js has components. Based on its official website, a component can look like this: <ol> <!-- Create an instance of the todo-item component --> <todo-item></todo-item> </ol> <script> Vue.component('todo-item', { template: '<li>This is a todo</li>' }) </script> But with the above code, the component will not show on the website, because the component is not registered. You need to register the component in a vue app like the following: <div id = "app">      <ol>           <!-- Create an instance of the todo-item component -->           <todo-item></todo-item>      </ol> </div> <script> Vue.component('todo-item', { template: '<li>This is a todo</li>' }) var app = new Vue({el:"#app"}); //or just new Vue({el:"#app"}); </script>

Installment Debt Data Calculation with Algorithm for Interest Rate

Image
This tool is used to calculate installment debt related data: Choose Item to be Calculated:  Loan Amount  Duration   Annual Interest Rate   Monthly Payment Monthly Payment:  dollar(s) Duration:  year(s) Annual Interest Rate:  % Loan Amount:  dollar(s) Calculate   Term Principal Paid Interest Remaining Debt Algorithm for Interest Rate Of all 4 items of installment debt calculation, loan amount, duration in month, annual interest rate and monthly payment, only the annual interest rate can not be derived by knowing the other 3. By looking at this formula, we just can't single out "r" and to calculate. Solution To calculate annual interest rate for the present value of an annuity, we use a method that is similar to binary search. Starting with an interes rate and calculate the monthly payment, since we kwow all the other variables. Then we compare the first result to the alr...

How to Make Responsive Tables and Images?

Image
When a table contains many columns, we need a y-axis scroll bar for users to see all the information in the table. Or, when an image contains a lot of information that we want to display for users to see, we a y-axis scroll bar. The responsive image is often used when we want to use a long math formula. In both cases, we can create a responsive table or image with a y-axis scroll bar. Here is how I do it: Wrap a table or image in a div tag and set its width to 100% and overflow to scroll. Set the targe table or image to a width that can comfortably display all information. If doing the above is not working, the y-axis scroll bar does not show up, try add a max-width with the same width with "width", because some website themes or CSS frameworks set max-width to 100% to all images. Responsive Design The responsive functionalilty is achieved by seting the width for a table or an image to a fixed size (not a percentage ) so that a y-axis scroll b...