Tuesday, February 28, 2023

lots of javascript recipes

Since I'm new to javascript and am trying to write some javascript code, lots of googling and some mis-steps. But useful, since loading json data and displaying can be done much, much faster with javascript rather than, for example, google apps script. Summarizing some "how-to"s below.
  • The addressing style using $ is usually used with jQuery. For example, 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    $(function () {
       // this runs on page load
       ourdropdownupdate();
       loadourdata();
    });


  • Javascript generally loads and executes from top to bottom linearly, except for async calls. So, within functions, for example, one would execute linearly. 

  • Global variables - variables declared outside function braces {} will be global variables. (But in google apps script, functions called from templated html will start execution from the top, as a separate thread, so the global variables initialized earlier would not be initialized for that execution.)

  • Returning Multiple Values from a Function - we need to either return an array or an object which has multiple properties.

  • Clear all rows in an html table except the first row
    var mytable = document.getElementById("mytableid");
    mytable.getElementsByTagName("tbody")[0].innerHTML = mytable.rows[0].innerHTML;
  • Create options in a dropdown list (select element in a form) -
    https://stackoverflow.com/questions/78932/how-do-i-programmatically-set-the-value-of-a-select-box-element-using-javascript
    https://www.w3schools.com/jsref/met_select_add.asp
    https://stackoverflow.com/questions/4618763/removing-all-option-of-dropdown-box-in-javascript
    var selecDay = document.getElementById("dateselector");
    selecDay.options.length = 0; // clear the select element of all options
    var option = document.createElement("option");
    var optiondate = new Date(optiondatemillisec);
    option.value = optiondate.toISOString().substring(0, 10);
    option.text = optiondate.toLocaleString('en-us', { day: 'numeric', month: 'short', year: 'numeric' })
    selecDay.add(option);


  • The function toISOString() (as used above) will generally return a string with zero offset - so, if we want the local time in the string, we need to get the offset and subtract it - not add it. 
    https://stackoverflow.com/questions/10830357/javascript-toisostring-ignores-timezone-offset
    javascript - Get month name from Date - Stack Overflow 
    var tzoffsetmilli = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
    var localtimestring = (new Date(gmtDateTime.getTime() - tzoffsetmilli)).toISOString();


  • How to format numbers by prepending 0 to single-digit numbers? - Stack Overflow
    var formattedNumber = ("0" + myNumber).slice(-2);

  • How to display the abbreviated name of the user's timezone (not GMT offset) in JavaScript? - Stack Overflow
    The method of getTimezoneShort() mentioned in the page above does not display strings like IST for Indian Standard Time, instead it shows GMT +5:30 etc. One could use some jerry-rigged code taking the first letter as mentioned here, but that is not guaranteed to work across many timezones. I just displayed "local time" instead, and displayed the full timezone string elsewhere, as obtained with
    var timeZoneStr = Intl.DateTimeFormat().resolvedOptions().timeZone;

  • How do I check if file exists in jQuery or pure JavaScript? - the similar syntax as this one can be used as a get() replacement, like below, replacing HEAD with GET.
    $.ajax({
                        url: pathname1,
                        type: 'GET',
         success: function (data) {
          schdata = JSON.parse(data);
         },
           error: function () {
            // try something else                            
         }
    });
  • If we do a setInterval(), we may need to do a clearInterval() if we want to stop it - otherwise, if the element checked inside the setInterval is not found, there would be an exception and all javascript processing will stop. For example, this time counter -
     
    <div id='typingdiv'>
    <h3 id='seccounter'> </h3>
    <script>
    // Set the date we're counting down to
    var sec = 1;

    // Update the count down every 1 second
    var x = setInterval(function() {
    try {
    document.getElementById("seccounter").innerHTML = sec + "s ";
    sec++;
    }
    catch (err) {
    // error because the setInterval cannot find the element
    // after the ajax completes and overwrites the div.
    clearInterval(x);
    }
    }, 1000);
    </script>

  • A useful way to debug is to add console.log(err) in catch (err) blocks - or console.log some other string at someplace else - and to watch the console on the html page with a right-click, Inspect, and the Console tab.

  • If we have an iframe and want to pass parameters to it (or, in general, we want to pass parameters to javascript on a page), we need to use GET requests and not POST requests - https://stackoverflow.com/questions/831030/how-to-get-get-request-parameters-in-javascript - 
    var queryString = location.search
    let params = new URLSearchParams(queryString)
    // example of retrieving 'id' parameter
    let id = parseInt(params.get("id"))
    console.log(id)

No comments:

Post a Comment