Roy Tang

Programmer, engineer, scientist, critic, gamer, dreamer, and kid-at-heart.

Blog Notes Photos Links Archives About

All entries tagged javascript.

You can subscribe to an RSS feed of this list.

Jan 2019

  • I’ve been working with Javascript for more than a decade. Last week while helping another developer debug a problem, I had to Google how to check if an element exists in a Javascript array, something superbasic, that one would expect most newbies to know. I’m sure I Google some superbasic thing at least once a week. It’s not embarassing or anything, it’s a common occurrence. I’m surely not alone. Just last night a tweet about this crossed my TL:

    read more (340 words)

    Posted by under post at #Javascript #Software Development
    Also on: twitter / 0 / 340 words

Dec 2017

  • How to specify that a column in the schema should be nullable?

    I tried adding a nullable attribute:

    var myFirstTDE = xdmp.toJSON(
      {
        "template": {
          "context": "/match",
          "collections": ["source1"],
          "rows": [
            {
              "schemaName": "soccer",
              "viewName": "matches",
              "columns": [
                {
                  "name": "id",
                  "scalarType": "long",
                  "val": "id",
                  "nullable": 0
                },
                {
                  "name": "document",
                  "scalarType": "string",
                  "val": "docUri"
                },
                {
                  "name": "date",
                  "scalarType": "date",
                  "val": "match-date"
                },
                {
                  "name": "league",
                  "scalarType": "string",
                  "val": "league"
                }
              ]
            }
          ]
        }
      }
    );
    
    tde.validate( 
      [myFirstTDE]
    );
    

    But this gave me a template error:

    "message": "TDE-INVALIDTEMPLATENODE: Invalid extraction template node: fn:doc('')/template/array-node('rows')/object-node()/array-node('columns')/object-node()[1]/number-node('nullable')"
    

    For a template defined using XQuery, adding nullable to the column works:

    <column>
      <name>ISSN</name>
      <scalar-type>string</scalar-type>
      <val>Journal/ISSN</val>
      <nullable>true</nullable>
    </column>
    

    How to do the same thing using JS/Json?

Nov 2017

Oct 2017

  • I’m trying out vis.js for generating graph visualization. For every edge in my graph, I have a number that describes the strength of the connection between two nodes. I’d like to render the vis.js graph such that the nodes that have stronger relationships (higher edge values) are closer together (edge length is shorter).

    I’ve set the relationship strength (an integer) as the “value” attribute for each edge, but this only seems to make the edge lines slightly thicker for higher values.

    What options should I be looking at? I’m not sure if this is supposed to be a function of vis’s physics-based stabilization.

    Thanks for advice!

Sep 2017

  • I have an HTML page with around 10 charts generated by chart.js (so these are canvas elements). I want to be able to export the page content into a PDF file.

    I’ve tried using jsPDF’s .fromHTML function, but it doesn’t seem to support exporting the canvas contents. (Either that or I’m doing it wrong). I just did something like:

        $(".test").click(function() {
      var doc = new jsPDF()
    
      doc.fromHTML(document.getElementById("testExport"));
      doc.save('a4.pdf')
    });
    

    Any alternative approaches would be appreciated.

  • I’m using ML8. I have a bunch of json documents in the database. Some documents have a certain property “summaryData”, something like:

    {
    ...(other stuff)...
      summaryData: {
        count: 100,
        total: 10000,
        summaryDate: (date value)
      }
    }
    

    However, not all documents have this property. I’d like to construct an SJS query to retrieve those documents that don’t have this property defined. If it was SQL, I guess the equivalent would be something like “WHERE summaryData IS NULL”

    I wasn’t sure what to search for in the docs. Any advise would be helpful.

Jul 2017

  • I’m using the demo of jsPlumb here:

    In this demo, there’s no way to move an existing connection to a different target node. Any idea how to do it?

    Some of the other examples have movable connections, but they also use specific endpoints on the nodes. I like this particular example where I can drag the connection endpoint to any point of the target node.

  • I’m trying out jsplumb. I have a copy of this demo: https://jsplumbtoolkit.com/community/demo/statemachine/index.html

    In this demo, when I drag one of the nodes outside of the canvas boundary, a scrollbar appears to indicate the canvas area has expanded. However, I still have to manually scroll the view to see the dragged node.

    I would like the view to automatically scroll when I drag a node beyond the edge. Same thing when dragging a new connector, I would like to automatically scroll the view - so I can choose to connect to a node currently outside the visible area. Any advice on how to do this?

    Secondary question: In the demo above the scrollbars appear as expected when I drag elements off the right or bottom of the canvas, but not when I drag them off the left edge or off the top edge. That is, if I drag a node upward off the canvas and drop it there, I no longer have any way of viewing that node or dragging it back down. Is there a way around this?

Jun 2017

Dec 2016

  • In JavaScript, referencing variables that are declared outside of a function’s scope can be tricky. If you have code like this: var btn = document.getElementById("BTN"); var test = 1; btn.onclick = function() { alert(test); } test = 2; The click handler above retains a reference to the test variable even though it falls out of scope as soon as the script block finishes execution. When you actually click the button, the alert will show the last value of the variable when the block finished execution (2) instead of the value at the time the function was initialized (1).

    read more (361 words)

Feb 2014

Mar 2013

Jul 2012

Dec 2011

Dec 2010

Sep 2010

Aug 2010

Jul 2010

Jan 2010

Dec 2009

Nov 2009

Oct 2009

  • I have a CRUD maintenance screen with a custom rich text editor control (FCKEditor actually) and the program extracts the formatted text as HTML from the control for saving to the database. However, part of our standards is that leading and trailing whitespace needs to be stripped from the content before saving, so I have to remove extraneous &nbsp; and <br> and such from the beginning and end of the HTML string.

    I can opt to either do it on the client side (using Javascript) or on the server side (using Java) Is there an easy way to do this, using regular expressions or something? I’m not sure how complex it needs to be, I need to be able to remove stuff like:

    <p><br /> &nbsp;</p>
    

    yet retain it if there’s any kind of meaningful text in between. (Above snippet is from actual HTML data saved by the tester)

  • Let’s say I attach a javascript “change” event handler to a select element, something that dispatches an ajax request to load some stuff from the server.

    This is fine in Firefox. However, in IE, the change event will fire every time you scroll rapidly through the combo box options using a mouse wheel. This is troublesome because it spams the server with requests, and there’s no guarantee the requests come back in the correct order, hence the client-side state may become inconsistent.

    Now, our previous workaround was that we would introduce a timeout to the change handler, such that it would wait a fraction of a second before actually dispatching the request. If in that short time, another change event comes in, we cancel the previous timeout and start a new one, thus preventing spamming multiple requests.

    Now, while this seems to be working, it’s a bit hackish and I’m wondering if there’s any better approach. Is there a different event we can hook to so that it doesn’t fire repeatedly when scrolling with the mouse? Or should we just disable mouse-wheeling altogether (onmousewheel="return false;")? Firefox does not seem to support mouse-wheeling thru combo boxes, but I’m not sure if disabling mouse wheeling is a serious usability no-no or something.

    Can anyone recommend other solutions?

Sep 2009

  • HTML/Javascript - I want to load images dynamically, and the images I’m going to load can be of varying aspect ratios.

    I want the images to fit into a specific area of the containing div - an area 40% of the containing div’s width and 80% of its height. Since they have varying aspect ratios, of course they will not always use up this entire area, but I want to resize them such that they don’t exceed the bounds. But I don’t know ahead of time whether I should specify the width or the height (and the partner attribute to auto) since I don’t know what the aspect ratio of the images will be ahead of time.

    Is there a CSS way to do this? Or I need to compute the required widths using javascript?

    PS I only need to do this in Firefox 3.5!

Aug 2009

  • Say I add events to an object using either addEventListener or attachEvent (depending on the browser); is it possible to later invoke those events programmatically?

    The events handlers are added/removed using an object like this:

    var Event = {
        add: function(obj,type,fn) {
            if (obj.attachEvent) {
                obj.attachEvent('on'+type,fn);
            } else {
                obj.addEventListener(type,fn,false);
            }
        },
        remove: function(obj,type,fn) {
            if (obj.detachEvent) {
                obj.detachEvent('on'+type,fn);
            } else {
                obj.removeEventListener(type,fn,false);
            }
        }
    }
    

    Or do I need to store copies of each handler and just add an Event.invoke(…) function?

    Edit: Also, jQuery is not an option :D

Jul 2009

  • Any idea for this?

    Problems encountered: Using screen.availHeight and screen.availWidth as the height and width params in window.open causes the browser size to include the taskbar, and positioning at (0, 0) ignores the possibility of the taskbar being up there.

    What I want is to open a new window with the size as if it was “maximized” by the user, i.e. it shouldn’t cover the windows taskbar.

    (Oh, and no need to remind me that users don’t like Javascript interfering with their browser windows, etc. This is for an internal intranet webapp…)

Jun 2009

  • Given the code below:

    function test() {
        document.forms[0].TEST[0].focus();
    }
    
    <form>
        <input type="button" value="Test" onclick="test()" />
        <input type="radio" name="TEST" value="A">A
        <input type="radio" name="TEST" value="B">B
    </form>
    

    In IE6, clicking the button doesn’t focus the control, unless I’ve already tabbed through the radio at least once, in which case it works. =/

    Any idea how I should be focusing the control? The above works perfectly fine in FF of course.

    Edit: I found that the control is being focused, except the highlight box around the radio button is not being rendered. (I can hit space to activate the radio button, and also use arrow keys to change the active button). So the question becomes: how can I force the focus highlighting box to render?

Mar 2009

Jan 2009

Dec 2008

Nov 2008

Aug 2008

Jul 2008

Jun 2008

Nov 2006

Apr 2006

Mar 2006

Feb 2006

Jan 2006

Sep 2005

May 2005

Apr 2005

Mar 2005

  • In Progress, But Sleepy

    As it may mention in the page title, I’m currently screwing around with the blogger template, so this blog may look a bit… um… screwy for a while. I’ve been wanting to toy around with Javascript hacks to extend the Blogger template functionality. The first thing I did was add some Javascript that allows you to show/hide individual posts on the page. But actually, I don’t really like it, I’ll remove it later.

    read more (274 words)