Roy Tang

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

Blog Notes Photos Links Archives About Now

All entries tagged javascript.

You can subscribe to an RSS feed of this list.

Jan 2019

I still Google the most basic things


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 / Tags: #Javascript #Software Development / Syndicated: 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

Basically the title. The client is complaining that when he zooms in, the text labels for the nodes are quite large. Is there a way to keep the node labels at a fixed font size even when zooming in or out?

From the nodes documentation (http://visjs.org/docs/network/nodes.html), there’s a scaling.label option, but it doesn’t seem to work. I think this is only relevant if I’m using values to scale the nodes.

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

The scenario is: the user can input a URL for an image file, then on form submit I want to download the file and submit it to the server. As if they had selected the file using an <input type='file' />.

Of course I can just do it on the server-side. But my question: how can I do this on the browser side via JavaScript? Is it possible?

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)

Posted by under post at / Tags: #javascript #Software Development / Syndicated: tumblr twitter / 0 / 361 words

Feb 2014

IE8 is giving me the slow-running script message on load of a page:

Stop running this script? A script on this page is causing your web browser to run slowly. If it continues to run, your computer might become unresponsive.

However, the webapp I’m debugging is fairly old and has a whole lot of scripts. Is there an easy way for me to find out which of those scripts is causing the problem?

Mar 2013

I’m trying to trace a slowdown on load of a web page in our application and there’s a ton of JavaScript to go through so I’d rather not process them individually.

I’m trying to see if there’s a way to list out all the event handlers added to $(document).ready() so that I would just look through those handlers to see what might be causing the problem.

Is there a way to do this?

Jul 2012

Dec 2011

Dec 2010

Sep 2010

If you want to use jquery ui autocomplete, your data must be “a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both”. This is from the documentation at http://jqueryui.com/demos/autocomplete/

Your server response does not follow the expected data type, you should modify suggest.php to post-process the data into label-value pairs.

As I understand it, you also want to perform a custom action when an item is selected from the autocomplete, so you should also add a handler for the ‘select’ event.

Aug 2010

You already have the lines logging your values array, was it so hard to add lines logging the other vars?

c1_arr = c1.split(';');  

The array created here is [‘font-color:#ff0000’, ‘'] - there is a blank second element since there’s nothing after the ‘;’ in the input string.

Then when you call:

values[1][i]= c1_arr[i].split(':');

c1_arr[1] is empty string, so values[1][1] is an array with only one element, empty string.

values[1][1][0] -> empty string values[1][1][1] -> undefined (no second element)

Posted by under notes at / Tags: #javascript #jquery #arrays / Imported from stackexchange / Syndicated: stackexchange / 0

If you use a hidden frame, the content won’t be displayed (hence “hidden”), I think you just mean to use an iframe. But this doesn’t fit your description of “without refreshing”, since you have to refresh the frame.

When loading the PHP file inside the frame, your PHP file just needs to generate HTML the same way you would generate a normal page. It’s the same whether the PHP file is loaded inside a frame or not.

Posted by under notes at / Tags: #php #javascript / Imported from stackexchange / Syndicated: stackexchange / 0

Jul 2010

Back story: I’m planning to implement a casual game to be deployed in a webapp, but I don’t want to use Flash, instead just plain Javascript. One benefit of Flash that I would want though is that it distributes a binary and not the source code so it’s easier to protect your code from being reused/stolen by somebody else, or to prevent the client from modifying the code to “cheat” in the game?

So my question is: what are the ways to similarly protect a Javascript application? Am I limited to the usual methods of using a code obfuscator? Will that be enough?

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)

Posted by under post at / Tags: #javascript #Meta #Software Development / Imported from roywantsmeat / Syndicated: blogger / 4 / 274 words