Posts

Showing posts from March, 2022

How to Update an Object in JavaScript

In JavaScripot, updating a variable is quite straitforward. We assign a nnew value to the variable like this. var name = "John"; name = "Joe"; //variable name has been chagned from John to Joe. Waht about an object? Updating a property of an object is the same way we do with varialbes. <script> var obj = { name:"John", age:10, call:function(){ console.log("My name is " + this.name + "."); } }; obj.age = 11; console.log(obj.age); // 11 </script> Updating mothods in an object We can also update the methods the same we way we do with updating object property <script> var obj = { name:"John", age:10, call:function(){ console.log("My name is " + this.name + "."); } }; obj.call(); //My name is John. obj.call = function(){ console.log("I'm " + this.age + " years old."); } obj.call(); //I'm 11 years old. </script> Creating new object...

The Copied Object Does Not Inherit Getter or Setter from the Origianal Object in JavaScript

When we copy an object using the three-dot operator, the setter and the getter of the object are not copied. the getter's initial value of be copied over to the new object as just its property and the setter will be undefined. var obj_1 = { count:1, price:100, get total(){ return this.count * this.price }, set priceSetter(value){ this.price = value; } } var objCopy_1 = {...obj_1}; console.log(objCopy_1); //{count: 1, price: 100, total: 100, priceSetter: undefined} Playground Count:<input oninput="obj_1.count = this.value;show_1.innerHTML = obj_1.total;" type="number" value="1" /> <div>The total is <span id="show_1"></span></div> Count:<input oninput="objCopy_1.count = this.value;show_2.innerHTML = objCopy_1.total;" type="number" value="1" /> <div>The total is <span id="show_2"></span></div> <script> var obj_1 = { c...

HTML Table Basics

We can create tables on the web browser. The HTML tagle is table The basic structure of a HTML table is the table row tag, the table head tag and the table data tag. The table head and table data tags work just like columns in Excel. Let's Experiment with table, table row and table data tags. Here is a table constructed with table row and data. ID Name Age 1 John 30 2 John 30 3 John 30 <table> <tr> <td>ID</td> <td>Name</td> <td>Age</td> </tr> <tr> <td>1</td> <td>John</td> <td>30</td> </tr> <tr> <td>2</td> <td>John</td> <td>30</td> </tr> <tr> <td>3</td> <td>John</td> <td>30</td> </tr> </table> No Borders The problem with the vanilla HTML table is that the table does ...

Web Color Design

Color is an esentialal element in web design. Even with a little deisign with color, out simple website can look more beautiful Color can be applied to text, background and border. When we geve a HTML componet a color, we can define the RGB, and and or just simply use the color names, like blue, yellow and red. CSS Color with A Name We can use the name of the color to style the text or the background, <div style="color: red;">red</div> red <div style="background-color: orange;">red</div> red Here Is A Table of Some of the Colors With Names Color Name Text Backdound Color azure azure azure aquamarine aquamarine aquamarine aquamarine aquamarine aquamarine aqua aqua aqua aliceblue aliceblue aliceblue antiquewhite antiquewhite antiquewhite darkred darkred darkred red r...

The Difference Between plot and newPlot Methods in Plotly.js

In Plotly.js, the basic methods to draw a plot are Plotly.plot and Plotly.newPlot and the 2 required parameter for both go them are the id of the plot container and data. If you don't give it data, Plotly.js will only draw an empty plot, so data is sort of required. Minialistic Example Plotly.newPlot( 'plotContainer_1', [{x:[1,2,3],y:[1,2,3]}], ); The Difference Between Plot and NewPlot The difference bwterrn Plotly.plot and Plotly.newPlot is that Plotly.plot will plot on top of the same plot without reploting the whole plot. Example of Using Plotly.plot() Click this button multiple times to see the effect. Plot function plot_1(){ var xArray = []; var yArray = []; for(let i = 0; i < 10; i++){ xArray.push(i); yArray.push(Math.random()); }; Plotly.plot( 'plotContainer_2', [{x:xArray,y:yArray}], ); }; Example of Using Plotly.newPlot() Plot function plot_2(){ var xArray = []; var yArray = []; for(let i = 0; i < 10; i++){ x...

How to Type Spaces In HTML Input And Display In the Browser

Image
When we type a space in an input and use it in JavaScript. The space will be recorded as text just like regular texts. Type In Multiple Spaces When we type some text with many spaces and displays the text in the browser, muiltple spaces will be parsed into one space, if they are connected. Type some text with spaces here: <input oninput="show_1.innerHTML = this.value" /><br /> <div id="show_1"></div> What does JavaScript Do to the Spaces? JavaScript does nothing to the spaces. It preservs all the spaces we type. The following code converts spaces into the letter "a". Space is represnted by \x20 in JavaScript. Type some text with spaces here: <input oninput="show_2.innerHTML = this.value.replace(/\x20/g,'a');" /><br /> <div id="show_2"></div> Why doesn't the Spaces Show in the Browser? Because the connected spaces are parsed into one space in HTML. ...

How to Remove All Spaces from an Array in JavaScript

We can use regular expression /\s/g to remove all spaces in JavaScript, but the problem is that it will also remove all line breaks when we want to keep the line breaks. The solution is that we can use /\x20/g instead of /\s/g wheer \s is space and \x20 is line break in JavaScript. Original String <textarea oninput = "show_1.innerText = this.value"></textarea> <div id = "show_1"></div> String with All Spaces Removed where Line Breaks are Also Removed We can remove all sapces from a sring using regular expression /\s/g. But the problem is we will also remove all line breaks too. <textarea oninput="show_2.innerText = this.value.replace(/\s/g,'')"></textarea> <div id="show_2"></div> String with All Line Breaks Removed <textarea oninput="show_3.innerText = this.value.replace(/\n/g,'')"></textarea> <div id="show_3"></div> ...

How to Change the Line Width of A Chart.js Line Chart

The default line width of a Chart.js line chasrt is 3 which is quite thick to my eyes. Here is how we can change the line width both indivisually or gloabally. The line width property is called borderWidth, which can found in both the dataset and the element namespace. Changing the borderWidth property in the dataset changes the line width for a single line, while chaging the borderWidth in the element changes all lines' width. We can find borderWidth for all lines in the options/elemets/line namespace. Changing Indivisual Line's Width Black Line Width: Red Line Width: Sample Code <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <canvas id="myChart"></canvas> <script> const labels = [ '1', '2', '3', '4', '5', '6', ]; const data = { labels: labels, datasets: [{ label: 'My First dataset...

How to Execute JavaScript Events Without Interacting with HTML Elements

HTML events are triggered by interacting with HTML elements, such as by clicking on a button or by entering into an input. However, we can actually execute the events without engaging the HTML elements. For example, we can execute a onclick event handler of a button without clicking on the button. Alert Execute the Above Button <button onclick = "alert('hi')" id = "myButton">Alert</button><br><br> <button onclick = "myButton.onclick()">Execute the Above Button</button> Why Can We Execute An Evenet Without Engaging with the HTML Element We can fire an event without touching the HTML element because an we can make a HTML element an obecjt and use its methods, which include all evenet handlers available, including onclick, onmouseove, and etc.. When do I Call An Event Without Engaging the HTML Elements I make an event executed without directly engaging with the HTML element, when I define the oninput eve...

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

Image
The image slide show I am making has no animation. The mechanism for displaying different slide is by using the display CSS property. The image with display none will not show, while the one with display block will. I will start build one that relys on HTML code then I will build one that relys on JavaScipt that renders the slide show onto the webpage. HTML Slideshow Setup A HTML image slide show can follow the following logic: An image is shown and the others are hidden, by defining the CSS display property to "block" to show and "none" to hide. An index is used to control the CSS display property of each slide with the initial index of 1. On initiation, all image tags for the slide show will be given the CSS property correspoding to whether it's shown or not. A left arrow and a right arrow are used to control the index with onclick event handlers. In order to position the left and right control...

How to Make Plotly.js or Chart.js Charts Responsive

Charts we make on web are often seen on mobile devices.  Then, the charts need to be responsive to the relatively small size of the mobile device. Charts made with Plotly.js or Chart.js are responsive in nature, but they both have the same problems: the charts look crowded on small screen and long title will be trucated on both the front end and back end. Also, when there are a lot of data points, the charts or plots will look even more crowded. Solutions I will add another <div> tag around the chart and assgin overflow scroll CSS property to it. And I will set the min-width for the original plot or chart container so that the chart can be scrolled on small screen. Non-responsive: Responsive: Plotly.js <div id="myPlot"></div> Chart.js <canvas id="myChart"></canvas> Plotly.js <div style="overflow: scroll;"> <div id="myPlot1" style="min...

HTML Tags and Inline CSS that Work In Plotly.js Title

When we create a plot object with Plotly.js, we throw in 3 basic parameters in the Plotly object which are the plot container id, data and layout, like this one: Plotly.newPlot('myDiv', data, layout); And in the layont object, there is a property, called title. The title property can be defined with an string, which will simply be just the title text that is going to display on the top of the plot.  I want to style my chart title when I use Plotly.js.; var layout = { title:`Plot Title` } Or in the text object within the title property. var layout = { title:{text:`Plot Title`} } Plot;y'js has some built-in title properties which we can use to style the title, sush as font color, family, size, padding, and position with x or y. var layout = { title: { text:'Plot Title', font: { family: 'Courier New, monospace', size: 24 }, xref: 'paper', x: 0.05, } }; Problems But I want to add a HTML tag...

JavaScrpit Function for Stock Valuation with Dividend DIscount Model

Image
One stock pricing technique is to use the dividend discount model which discount all estimated dividends back to present and sum them all up to get the target stock price. Discounting a dividend to present is the same with the present value of the dividend, where the risk free rate is used. The dividend discount model assume the stock pays dividends forever. There are variations of assumption for calculating the stock price based on dividend discount model: The risk free rate is constant. The risk free rate following a normal distribution. The stock pays constant dividends. The stock pays increasing(decreasing) dividends with a constant rate. The stock pays differest dividends with rates that follow a normal distribution. Formula of Dividend Discount Model With A Constant Risk Free Rate and A Constant Dividend Changing Rate With a stock paying constant dividends, one can just put 0 into d in the above formula. JavaScrpit Fu...

JavaScript Function for Bond Pricing

Image
Bonds are priced based on all present values of all coupons and the face values. Present value means how much it is worth to pay right now for something that we will get in the future. The counterpart is future value, which is the value we are expecting to get if we invest right now. Bond Pricing Math Formula For a 10-year bond the price is the following: For a bond with a different maturity, we can just calculate its value with a little adjustment to the above formula by adding more coupon terms. JavaSript Algorithm for Bond Pricing Based on the bond pricing formula above, we see there are 4 factors that dictate the bond price, coupons, fave value, interes rate(r) and bond maturity. Normally the fave value is $100, so in the following code, I will set the default to 100 for the face value. Coupons are the result of the face value times the coupon rate. The bond pricing function take 4 parameters, coupon rate, interest rate and maturity. Playgr...

Execute Other Events With Keyboard Events

When users use a webapp or browse a website. They sometimes want to use the keyboard to do somehitng, such as pressing "enter" to submit a form or press "esc" to escape some actions How to find all the key code? Check out this article. For exampe, if wa want to clear an input box with pressing the "eac" key. Type in the input box then press "esc" key to see the effect. <input id="myInput" /> <script> window.onkeydown = () =>{ if(event.keyCode == 27){ myInput.value = ""; }; }; </script> Fire an Event If we want to fire an event with a press on a key, we just assign functions to that keycode But if the rvent which is already listened by an HTML element such as a button and the event consists of many functions. In order to make our code more manageble, we can just use the element object and call the method corresponding to the event listener For example, if we want to do exact the same thing w...

NaN Is Actually A Number In JavaScript

What is NaN in JavaScript NaN is short for "not a number". Butm wait, NaN is actually a number var number = Number('sometext'); console.log(number); // NaN console.log(typeof(number)); // number Varify if something is NaN Sometimes we want to veriru if something is a number then proceed execution of following code. But the following code will not work if(Number(something) == NaN){...} if(Number(something) == "NaN"){...} We need to use this: if(Number(something){...} if(!Number(something)){...} This works because NnN kind of means 'true' var number = Number('sometext'); console.log(number == false); // false console.log(!number == true); // true console.log(!!number == false); // true if(number){ console.log('This is not a NaN'); }else{ console.log('This is a NaN'); }; //This is a NaN

Common HTML Keycodes

Here are commonly used key codes. When we want to submit a form, users are expecting to press enter as to press sumbit button Submit window.onkeydown = function(){ if(event.keyCode == 13){ alert('submitted') } Here are some common keycodes Key Code enter 13 esc 27 space 32 Here you can look up keycode

How to Use onkeydown, onkeypress and onkeyup HTML Event Listeners

HTML event liseteners onkeydown, onkeypress and onkeyup will only be called on HTML elements that can be focused, sush as inputs, buttotn or anchor tags. If an anchor is not assigned with any target, it cannot be focused. The order of execution for onkeydown, onkeypress and onkeyup is onkeydown, onkeypress and onkeyup. <input onkeydown="show.innerHTML = 'keydown, '" onkeypress="show.innerHTML += 'keypress, '" onkeyup="show.innerHTML += 'keyup'" /> <div id="show"></div> When do I Use onkeyup I sue onkeyup event listener when I set an input to accept only numbers. As in this article, I wrote about inputs with type number can still be tryped in abnormal numbers suash 00123 or 14-4-1. I can use onkeydown or onkeypress in this validation, because I would not be able to type in negative numbers Try the following inputs to see the different effect, I also include oninput eveent listenr which fires a...