Best javascript questions in June 2011

parseInt(null, 24) === 23... wait, what?

115 votes

Alright, so I was messing around with parseInt to see how it handles values not yet initialized and I stumbled upon this gem. The below happens for any radix 24 or above.

parseInt(null, 24) === 23 // true

I tested it in IE, Chrome and Firefox and they all alert true, so I'm thinking it must be in the specification somewhere. A quick Google search didn't give me any results so here I am, hoping someone can explain.

I remember listening to a Crockford speech where he was saying typeof null === "object" because of an oversight causing Object and Null to have a near identical type identifier in memory or something along those lines, but I can't find that video now.

Try it: http://jsfiddle.net/robert/txjwP/

Edit Correction, a higher radix returns diffferent results, 32 returns 785077
Edit 2 From zzzzBov: [24...30]:23, 31:714695, 32:785077, 33:859935, 34:939407, 35:1023631, 36:1112745


tl;dr

Explain why parseInt( null, 24 ) === 23 is a true statement.

It's converting null to the string "null" and trying to convert it. For radixes 0 through 23, there are no numerals it can convert, so it returns NaN. At 24, "n", the 14th letter, is added to the numeral system. At 31, "u", the 21st letter, is added and the entire string can be decoded. At 37 on there is no longer any valid numeral set that can be generated and NaN is returned.

js> parseInt(null, 36)
1112745

>>> reduce(lambda x, y: x * 36 + y, [(string.digits + string.lowercase).index(x) for x in 'null'])
1112745

Javascript Shorthand for getElementById

49 votes

Is there any shorthand for the JavaScript document.getElementById? Or is there any way I can define one? It gets repetitive retyping that over and over.

var $ = function( id ) { return document.getElementById( id ); };

$( 'someID' )

Here I used $, but you can use any valid variable name.

var byId = function( id ) { return document.getElementById( id ); };

byId( 'someID' )

What does "var FOO = FOO || {}" mean in Javascript?

31 votes

Looking at an online source code I came across this at the top of several source files.

var AEROTWIST = AEROTWIST || {};
AEROTWIST.WebGLEasing = new function() { 
    // bunch of code here
}

But I have no idea what || {} does.

I know {} is equal to new Object() and I think the || is for something like "if it already exists use its value else use the new object.

Why would I see this at the top of a source file?

Your guess as to the intent of || {} is pretty close.

This particular pattern when seen at the top of files is used to create a namespace, i.e. a named object under which functions and variables can be created without unduly polluting the global object.

The reason why it's used is so that if you have two (or more) files:

var MY_NAMESPACE = MY_NAMESPACE || {};
MY_NAMESPACE.func1 = {
}

and

var MY_NAMESPACE = MY_NAMESPACE || {};
MY_NAMESPACE.func2 = {
}

both of which share the same namespace it then doesn't matter in which order the two files are loaded, you still get func1 and func2 correctly defined within the MY_NAMESPACE object correctly.

The first file loaded will create the initial MY_NAMESPACE object, and any subsequently loaded file will augment the object.

Usefully, this also allows asynchronous loading of scripts that share the same namespace which can improve page loading times. If the <script> tags have the defer attribute set you can't know in which order they'll be interpreted, so as described above this fixes that problem too.

The benchmark:

JsPerf

The invariants:

var f = function() { };

var g = function() { return this; }

The tests:

Below in order of expected speed

  • new f;
  • g.call(Object.create(Object.prototype));
  • new (function() { })
  • (function() { return this; }).call(Object.create(Object.prototype));

Actual speed :

  1. new f;
  2. g.call(Object.create(Object.prototype));
  3. (function() { return this; }).call(Object.create(Object.prototype));
  4. new (function() { })

The question:

  1. When you swap f and g for inline anonymous functions. Why is the new (test 4.) test slower?

Update:

What specifically causes the new to be slower when f and g are inlined.

I'm interested in references to the ES5 specification or references to JagerMonkey or V8 source code. (Feel free to link JSC and Carakan source code too. Oh and the IE team can leak Chakra source if they want to).

If you link any JS engine source, please explain it.

The problem is that you can inspect the current source code of various engines, but it won't help you much. Don't try to outsmart the compiler. They'll try to optimize for the most common usage anyway. I don't think (function() { return this; }).call(Object.create(Object.prototype)) called 1,000 times has a real use-case at all.

"Programs should be written for people to read, and only incidentally for machines to execute."

Abelson & Sussman, SICP, preface to the first edition

24 votes

TL;DR:

Do we need factories/constructors in prototypical OO? Can we make a paradigm switch and drop them completely?

The BackStory:

I've been toying with doing prototypical OO in JavaScript lately and find that 99% of OO done in JavaScript is forcing classical OO patterns into it.

My take on prototypical OO is that it involves two things. A static prototype of methods (and static data) and a data binding. We don't need factories or constructors.

In JavaScript these are Object literals containing functions and Object.create.

This would mean we can model everything as a static blueprint/prototype and a data binding abstraction that's preferably hooked straight into a document-style database. I.e. objects are taken out of the database and created by cloning a prototype with the data. This would mean there is no constructor logic, no factories, no new.

The Example code:

An pseudo example would be :

var Entity = Object.create(EventEmitter, {
    addComponent: {
        value: function _addComponent(component) {
            if (this[component.type] !== undefined) {
                this.removeComponent(this[component.type]);
            }

            _.each(_.functions(component), (function _bind(f) {
                component[f] = component[f].bind(this);
            }).bind(this));

            component.bindEvents();

            Object.defineProperty(this, component.type, {
                value: component,
                configurable: true
            });

            this.emit("component:add", this, component);
        }
    },
    removeComponent: {
        value: function _removeComponent(component) {
            component = component.type || component;

            delete this[component];

            this.emit("component:remove", this, component);
        }
    }
}

var entity = Object.create(Entity, toProperties(jsonStore.get(id)))

The minor explanation:

The particular code is verbose because ES5 is verbose. Entity above is a blueprint/prototype. Any actual object with data would be created by using Object.create(Entity, {...}).

The actual data (in this case the components) is directly loaded from a JSON store and injected directly into the Object.create call. Of course a similar pattern is applied to creating components and only properties that pass Object.hasOwnProperty are stored in the database.

When an entity is created for the first time it's created with an empty {}

The actual Questions:

Now my actual questions are

  • Open source examples of JS prototypical OO?
  • Is this a good idea?
  • Is it in-line with the ideas and concepts behind prototypical OOP?
  • Will not using any constructors/factory functions bite me in the ass somewhere? Can we really get away with not using constructors. Are there any limitations using the above methodology where we would need factories to overcome them.

As per your comment that the question is mainly "is constructor knowledge necessary?" I feel it is.

A toy example would be storing partial data. On a given data set in memory, when persisting I may only choose to store certain elements (either for the sake of efficiency or for data consistency purposes, e.g. the values are inherently useless once persisted). Let's take a session where I store the user name and the number of times they've clicked on the help button (for lack of a better example). When I persist this in my example, I do have no use for the number of clicks, since I keep it in memory now, and next time I load the data (next time the user logs in or connects or whatever) I will initialise the value from scratch (presumably to 0). This particular use case is a good candidate for constructor logic.

Aahh, but you could always just embed that in the static prototype: Object.create({name:'Bob', clicks:0}); Sure, in this case. But what if the value wasn't always 0 at first, but rather it was something that required computation. Uummmm, say, the users age in seconds (assuming we stored the name and the DOB). Again, an item that there is little use persisting, since it will need to be recalculated on retrieval anyway. So how do you store the user's age in the static prototype?

The obvious answer is constructor/initialiser logic.

There are many more scenarios, although I don't feel the idea is much related to js oop or any language in particular. The necessity for entity creation logic is inherent in the way I see computer systems model the world. Sometimes the items we store will be a simple retrieval and injection into a blueprint like prototype shell, and sometimes the values are dynamic, and will need to be initialised.

UPDATE

OK, I'm going to try for a more real-world example, and to avoid confusion assume that I have no database and need not persist any data. Let's say I'm making a solitaire server. Each new game will be (naturally) a new instance of the Game prototype. It is clear to me that their is initialiser logic required here (and lots of it):

I will, for example, need on each game instance not just a static/hard-coded deck of cards, but a randomly shuffled deck. If it were static the user would play the same game every time, which is clearly not good.

I may also have to start a timer to finish the game if the player runs out. Again, not something that can be static, since my game has a few requirements: the number of seconds is inversely related to the number of games the connected player has won so far (again, no saved info, just how many for this connection), and proportional to the difficulty of the shuffle (there is an algorithm that according to the shuffle results can determine the degree of difficulty of the game).

How do you do that with a static Object.create()?

How to overcome this security issue

22 votes

I have implemented an ajax-polling script that calls an action in the server Controller every 10 seconds. With the response, I replace the content of a div:

function getFoo() {
    var link = '/Secure/GetFoo';

    $.post(link, function (response) {
        $('#FooSection').replaceWith(response);
    });

    setTimeout("getFoo();", 10000);
}

This is done through https. After some time of being "idle", IE displays the following message:

This page is accessing information that is not under its control. This poses a security risk. Do you want to continue?

If the user clicks Yes, the page is redirected to the div displaying the response only. If the user clicks No, nothing happens, but the div container will not be refreshed.

I know I can suppress this message through browser settings, but that will just bring me to a default Yes selection as per the above dialog.

A similar issue has been asked before, but unfortunately there hasn't been any solution. I basically want to make my ajax-polling work even on a secure connection. Any ideas?

You should never see that dialog on an Internet-Zone page. By default, this operation is silently and automatically blocked in the Internet Zone.

There are two root causes for that dialog to appear in the Intranet zone:

1> Attempting to do a cross-origin request using the XMLHTTPRequest object (http://blogs.msdn.com/b/ieinternals/archive/2011/04/22/ie-security-prompt-page-accessing-cross-domain-information-not-under-its-control.aspx)

2> Attempting to navigate an OBJECT Tag hosting HTML to a cross origin page.

You can avoid case #1 by using XDomainRequest instead of XMLHTTPRequest. You can avoid case #2 by using an IFRAME instead of an OBJECT tag.

IE6: Background-Image Load Event

18 votes

I am displaying a bunch of thumbnail images and the latency can be very high (over a VPN) so I send all the thumbnails in a single file (like a sprite) and set the CSS background-image and background-position properties of a div to show the thumbnails. The problem I'm having is with IE6 and figuring out when the image has loaded... I'm using the BackgroundImageCache hack:

document.execCommand("BackgroundImageCache",false,true);

To check when the image is loaded I use this code:

$('<img>').attr('src', 'ThumbSpriteTest.png').load(function() {
    $('.Thumbnails').css('background-image', 'url(ThumbSpriteTest.png)');
});

This works in every browser I've tried except IE6... even with the cache hack it is loading the image, firing the event, setting the background-image property and downloading the image again (and my .Thumbnail elements are blank while it re-downloads).

It seems to me that the cache hack is only changing the behavior of the CSS references and not the img tag. How can I tell when the background image is loaded without downloading it twice? Is it possible in IE6?

EDIT: Using: document.execCommand("BackgroundImageCache",true,true); seems to work (with both parameters as 'true'). I'm having trouble finding any documentation on the BackgroundImageCache command and it's parameters (I've found plenty of examples of using it to fix the CSS problem, but they all use false,true as parameters and don't explain them)... the bounty is still good for anyone with good information/documentation on the BackgroundImageCache command and it's parameters!

(I'm not sure why I'm excited to find something that works after wasting so many hours due to IE's shortcoming)

This is definitely poorly documented, as it is considered a hotfix for ie6, and will stay that way, seeing this is already fixed in ie8. Anyway, here is what is dug up bout it.

execCommand method: http://msdn.microsoft.com/en-us/library/ms536419(v=vs.85).aspx

 bSuccess = object.execCommand(sCommand [, bUserInterface] [, vValue]);
 //sCommand is the name of command to execute
 //[bUse...] is to give permission to display a dialog window (if applicable)
 //[vValue] value to pass as parameter to the command

[bUserInterface]: is just a Boolean indicator for a dialog box, that is not used by all the possible command. But is used for example to save files / create link / etc... Eg: http://man.ddvip.com/web/dhtml/constants/createlink.html

So you may want to check if this value works when set to false, it should work in theory... But hotfixes can break for funny reasons.

About the hotfix: http://support.microsoft.com/kb/823727

Anyway, this feature only appear as a patch to IE6. So dun assume it will work for all ie6 browser. While it was introduced to prevent multiple loading + leakages, and not "caching" the way you are using it, it still does what the name suggests (hopefully). So dun be surprised it hiccups on the way on unpatched versions (auto update should fix this though)

With that warning, please catch the execution for the success or fail Boolean values, if you have features dependent on it. And I guess make the best with what you have (to be sad enough to be forced to support ie6)

JavaScript pass scope to another function

14 votes

Is it possible to somehow pass the scope of some function to another?

e.g.

function a(){
   var a = 5;
   var obj = {..};
   b(<my-scope>);
}
function b(){
   //access a or obj....

}

Update: I rather access it directly, i.e. not using anything like this.a/this.obj, just user o/obj directly

The only way to truly get access to function a's private scope is to declare b inside of a so it forms a closure over them. Since you've named a function and a variable the same thing, I've changed the a variable to x.

Direct Access

  1. Declare b inside of a.

    function a() {
       var x = 5,
          obj = {};
       function b(){
          // access x or obj...
       }
       b();
    }
    
    a();
    
  2. If you don't want b inside of a, then you could have them both inside a larger container scope:

    function container() {
       var x, obj;
       function a(){
          x = 5;
          obj = {..};
          b();
       }
       function b(){
          // access x or obj...
       }
    }
    
    container.a();
    

These are the only ways you're going to be able to use a's variables directly in b without some extra code to move things around. If are content with a little bit of "help" and/or indirection, here are a few more ideas.

Indirect Access

  1. You can just pass the variables as parameters, but won't have write access except to properties of objects:

    function a() {
       var x = 5,
          obj = {};
       b(x, obj);
    }
    
    function b(x, obj){
       // access x or obj...
       // changing x here won't change x in a, but you can modify properties of obj
    }
    
    a();
    

    As a variation on this you could get write access by passing updated values back to a like so:

    // in a:
    var ret = b(x, obj);
    x = ret.x;
    obj = ret.obj;
    
    // in b:
    return {x : x, obj : obj};
    
  2. You could pass b an object with getters and setters that can access a's private variables:

    function a(){
       var x = 5,
          obj = {..},
          translator = {
             getX : function() {return x;},
             setX : function(value) {x = value;},
             getObj : function() {return obj;},
             setObj : function(value) {obj = value;}
          };
       b(translator);
    }
    
    function b(t){
       var x = t.getX(),
          obj = t.getObj();
    
       // use x or obj...
       t.setX(x);
       t.setObj(obj);
    
       // or you can just directly modify obj's properties:
       obj.key = value;
    }
    
    a();
    

    The getters and setters could be public, assigned to the this object of a, but this way they are only accessible if explicitly given out from within a.

  3. And you could put your variables in an object and pass the object around:

    function a(){
       var v = {
          x : 5,
          obj : {}
       };
       b(v);
    }
    
    function b(v){
       // access v.x or v.obj...
       // or set new local x and obj variables to these and use them.
    }
    
    a();
    

    as a variation you can construct the object at call time instead:

    function a(){
       var x = 5,
          obj = {};
       b({x : x, obj: obj});
    }
    
    function b(v){
       // access v.x or v.obj...
       // or set new local x and obj variables to these and use them.
    }
    
    a();
    

What is the reason behind using 'instanceof function() {}'?

13 votes

On Mozilla Developer Center, there is a page about the Function.prototype.bind function and provides a compatibility function for browsers which do not support this function.

However, when analyzing this compatibility code I cannot find out why they use instanceof nop. nop has been set to function() {}. What part of the ECMA specification on bind does this correspond with? And what variables are an instance of function() {}?

The following returns false, so I don't completely know what it is used for. What things return true when doing an instanceof function() {} check?

(function() {}) instanceof (function() {}) // false

The code is as follows:

Function.prototype.bind = function( obj ) {
    if(typeof this !== 'function')
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');

    var slice = [].slice,
        args = slice.call(arguments, 1), 
        self = this, 
        nop = function () {}, 
        bound = function () {
          return self.apply( this instanceof nop ? this : ( obj || {} ), 
                              args.concat( slice.call(arguments) ) );    
        };

    bound.prototype = this.prototype;

    return bound;
};

Someone edited out the part that makes it useful. Here's what it used to look like:

Function.prototype.bind = function( obj ) {
    var slice = [].slice,
    args = slice.call(arguments, 1), 
    self = this, 
    nop = function () {}, 
    bound = function () {
        return self.apply( this instanceof nop ? this : ( obj || {} ), 
                            args.concat( slice.call(arguments) ) );    
    };

    // These lines are the important part
    nop.prototype = self.prototype;
    bound.prototype = new nop();

    return bound;
};

I answered another question that was asking the same thing (but when the code was correct) here: mozilla's bind function question.

The reason for the this instanceof nop check is so that if you call the bound function as a constructor (i.e. with the new operator), this is bound to the new object instead of whatever you passed to bind.

To explain the "important part", nop is basically getting inserted into the prototype chain so that when you call the function as a constructor, this is an instance of nop.

So if you run var bound = original.bind(someObject); the prototype chain will look like this:

  original
     |
    nop
     |
   bound

My guess for why they used nop instead of this instanceof self is so that the bound function would have it's own prototype property (that inherits from self's). It's possible that it's not supposed to which could be why it got partially edited out. Regardless, the code as it is now is not correct, but will work as long as you don't use the function as a constructor.

What would be the most ethical way to consume content from a site that is not providing an API?

13 votes

I was wondering what would be the most ethical way to consume some bytes (386 precisely) of content from a given Site A, with an application (e.g. Google App Engine) in some Site B, but doing it right, no scraping intended, I really just need to check the status of a public service and they're currently not providing any API. So the markup in Site A has a JavaScript array with the info I need and being able to access that let's say once every five minutes would suffice.

Any advice will be much appreciated.

UPDATE:

First all thanks much for the feedback. Site A is basically the website of the company that currently runs our public subway network, so I'm planning to develop a tiny free Android app for anyone to have not only a map with the whole network and its stations but also updated information about the availability of the service (and those are the bytes I will eventually be consuming), etcétera.

There will be some very differents points of view, but hopefully here is some food for thought:

  1. Ask the site owner first, if they know ahead of time they are less likely to be annoyed.
  2. Is the content on Site A accessible on a public part of the site, e.g. without the need to log in?
  3. If the answer to #2 is that it is public content, then I wouldn't see an issue, as scraping the site for that information is really no different then pointing your browser at the site and reading it for yourself.
  4. Of course, the answer to #3 is dependent on how the site is monetised. If Site A provides advertistment for generating revenue for the site, then it might not be an idea to start scraping content, as you would be bypassing how the site makes money.

I think the most important thing to do, is talk to the site owner first, and determine straight from them if:

  1. Is it ok for me to be scraping content from their site.
  2. Do they have an API in the pipeline (simply highlighting the desire may prompt them to consider it).

Just my point of view...

How to know the reason of blur?

12 votes

How can I know which event caused a blur event in jQuery?

Blur event triggered using click or tab etc. How can I know this blur event is due to click or tab?

If you are trying to do two different things depending on which method was used, bind handlers to listen for .click() and .keyup(), then check for the keycode

var k = (window.event) ? event.keyCode : e.keyCode;

Or something on the order of this if you need

$(document).bind("click keyup", function(){
   //check keycode
   var e = (window.event);
   var k = (e)?event.keyCode:e.keyCode;
   if(k==9){
      //tab code
   }else if(e.type=='click'){
      //click code
   }

});

What does a script-Tag with src AND content mean?

12 votes

Example from Googles +1 button:

<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
      {"parsetags": "explicit"}
</script>

The script Tag has a src-Attribute and content. What does this mean and how does it work?

Different browsers treat this differently. Some run the content only if the src is included without error. Some run it after attempting to include the src script, regardless of success. Since this behaviour is unreliable (and prohibited in HTML5), it should be avoided.

Google isn't relying an any specific behaviour. Since the content is just an object literal (a value), executing it would not actually do anything except cause a silent error. Google's code looks at the contents of the script tag itself, and adjust its behaviour based on that.

problem in file upload

11 votes

I have the following markup:

  <select multiple="multiple" id="targetFilesList"  style="width:200px;height:110px;">
   </select>
   <input type="button" value="Get" id="btnGet" />

and following javascript:

    $(function()
    {
        $('#btnGet').click(function()
        {
            var fileupload = $("<input type='file' name='filetoupload' style='visibility:hidden;'/>");
            $('body').append(fileupload);

            fileupload[0].onchange = function()
            {
                $('#targetFilesList').append('<option >' + fileupload.val() + '</option>');
                return false;
            }
            fileupload.click();
        });
    });

Scenario is that i have to upload multiple files and once user has chosen the file to be uploaded i have to show the file name to user.Then,on submitting the form i will upload all the files.For this,on clicking the get button i am adding a fileupload control dynamically and initialise onchange event of the fileupload control just added. The problem in chrome 12 on clicking get button fileupload control does not get opened but in firefox4 and ie8 it is working. Any idea why?

To get it working on Chrome 12, you can just add it into a window timeout of 0, like this:

window.setTimeout(function(){
   fileupload.click();   
},0);

Why exactly it behaves like this, I am not sure. The first time I encountered the problem I tried it with a longer interval, reducing it all the time to see how low you could get it, until I noticed it doesn't even need a delay. The obvious answer would be that it isn't actually ready in DOM by the time you trigger the click (element is there, but is the appropriate events for it?).

example: http://jsfiddle.net/HgEga/

Reason for .get() without index in jQuery API?

10 votes

Let's say that I've got a page which extracts some image sources like so:

<div id="d">
  <img src="foo.gif"/>
  <img src="bar.gif"/>
  <img src="gah.gif"/>
</div>
<script type="text/javascript">
  var srcs = $('div#d > img').map(function(){return this.src});
  // srcs => ['foo.gif', 'bar.gif', 'gah.gif']
</script>

Note that srcs is not a JavaScript Array but an array-like object; we know this because of the fact that we can make jQuery API calls on objects returned by the selector and the fact that srcs.constructor != Array.

The jQuery API provides a .get() method which, when given no argument, returns a "standard" Array. Is there a compelling reason to use a standard Array instead of an array-like object or is this method just included for completeness?

[Edit]

To put it another way - what are the differences between a JavaScript Array and the array-like object returned by a jQuery selector?

It allows you to use standard array methods which jQuery doesn't have, such as push.

In particular, jQuery objects are intended to be immutable, whereas arrays are not.

Chrome AJAX on page-load causes "busy cursor" to remain

10 votes

In Google Chrome, AJAX called within $(function(){....}); seems to keep the page loading.

I have a site with a few pages with tabs. Because I'm using cheap godaddy hosting, I want the page to load as fast as possible. I thus want to load a page on 1 tab and then in the background use AJAX to load the other tabs. When I run AJAX from

$(function(){
    /*AJAX CODE HERE */
});

The cursor shows the page as loading for a long time (http://jsfiddle.net/mazlix/7fDYE/9/)

I have figured out a way (in chrome atleast) to somewhat fix that using setTimeout(); (http://jsfiddle.net/mazlix/7fDYE/8/), but this only works if you correctly predict when the window finishes fully loading and obviously makes it take longer to load. I want a way to load content via AJAX immediately after the page loads, so no "busy-cursor" is displayed while waiting for the returned AJAX.

Google Chrome shows Loading Indicator as long as there are no new queries to servers. While the loading indicator is shown, all new requests are causing Chrome to extend the time the indicator is shown. Furthermore, when esc is pressed while the indicator is shown, all requests are aborted! These include AJAX requests and even Flash requests! Take a look at this question: i thought it was because of Youtube, but it turned to be Chrome's usual behavior.

The only way to avoid "extending" the time Loading indicator is shown, is making the requests after the loading indicator is hidden: i.e. when all queries to server are completed. JQuery's documentation on .load() says:

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

So, if you're sure that there are only images, scripts and frames on your page, window.load() will be fired just when you need it. Adding setTimeout() to it will work as you like. Here is an example: http://jsfiddle.net/7fDYE/22/

If there are other requests being made before your request, you should wait for them to be completed! For example, you know that besides the images/scripts etc. you have 3 more AJAX requests before the page loads. You can have something like this:

var loaded=0,needsToBeLoaded=4; //3 AJAX + window
function onLoad(){
    loaded++;
    if(loaded==needsToBeLoaded){
         //do the AJAX request   
    }
}
window.load(onLoad);
// add onLoad() to all 3 AJAX request handlers

I'm not sure what you can do with Flash requests...

Generating sound on the fly with javascript/html5

10 votes

Is it possible to generate a constant sound stream with javascript/html? For example, to generate a perpetual sine wave, I would have a callback function, that would be called whenever the output buffer is about to become empty:

function getSampleAt(timestep)
{
    return Math.sin(timestep);
}

(The idea is to use this to make an interactive synth. I don't know in advance how long a key will be pressed, so I can't use a fixed length buffer)

Using the HTML5 audio element

Cross-browser generative sustained audio using JavaScript and the audio element isn't currently possible, as Steven Wittens notes in a blog post on creating a JavaScript synth:

"...there is no way to queue up chunks of synthesized audio for seamless playback".

Using the Web Audio API

The Web Audio API was designed to facilitate JavaScript audio synthesis. The Mozilla Developer Network has a Web Based Tone Generator that works in Firefox 4+ [demo 1]. Add these two lines to that code and you have a working synth with generative sustained audio upon keypress [demo 2 - works in Firefox 4 only, click the 'Results' area first, then press any key]:

window.onkeydown = start;  
window.onkeyup = stop;

The BBC's page on the Web Audio API is worth reviewing too. Unfortunately, support for the Web Audio API doesn't extend to other browsers yet.

Possible workarounds

To create a cross-browser synth at present, you'll likely have to fall back on prerecorded audio by:

  1. Using long prerecorded ogg/mp3 sample tones, embedding them in separate audio elements and starting and stopping them upon keypress.
  2. Embedding an swf file containing the audio elements and controlling playback via JavaScript. (This appears to be the method that the Google Les Paul Doodle employs.)

Alternative to Captcha?

10 votes

I have a simple reg form (Name, Email, Password) on my website and im looking to implement some sort of anti-bot/spam protection, Captcha seems like a very long winded way, plus they really annoy me when I see them on sites. Has anybody an alternative method to protecting against spam which is lightweight and simply integrated?

One alternative is to use a hidden form field as a honeypot for bots. This field can be filled using an appropriate value from Javascript, or it can just be left blank. Either way, if the value isn't what you expect, then you can treat the submission as spam. This won't stop bots that are specifically targeting your site, but it will stop most of the common spam bots that just see a form and fill it out.

Representing time periods in the UI and database

9 votes

I've recently adopted a project with an Employee model that needs to contain the person's available hours as an attribute.

The existing form uses 168 checkboxes to represent each hour in the week, and stores the information as seven 24 bit binary strings in the database, each bit acting as a boolean true or false for its corresponding hour in that day.

I'd really like to transition to something a little more elegant and manageable, but I haven't been able to come up with any simple solutions that match the existing implementation's flexibility.

Storing time periods as start and end times can be just as tedious to input when there can be multiple per day, and would likely make querying for availability at a particular time more complicated.

Is there a best practice for dealing with this type of information, both in the user interface and the database structure?

I would model the data in the database this way.

Employee/Day/Hour Relationship

There's a many to many relationship between the employees and hours for each day of the week.

On the UI side, you could use checkboxes for the days and multiselect list boxes to set the hours for the given day.

Why do big sites use 'bad practices'?

8 votes

I often see articles, posts and comments something like:

  • globals are bad in javascript
  • script tags should be at bottom of page
  • CSS should be in external files and at the top of page
  • scripts should be in external files, not plain script-tags.
  • etc.

I've looked up the HTML source of some big sites and have noticed that they have a lot of plain javascript and CSS inside HTML markup. JavaScript and HTML are note always obfuscated, and so on.

There are quite a few separate issues here.

  1. What you see when you "view source" is not usually what they develop with. It's usually a compressed / optimised form generated from "source" code.
  2. Claims about what is "best practice" are necessarily generic, and don't apply to all scenarios (especially if you're a big site and need specialised optimisation). These guidelines should be considered individually for each project.
  3. Best practice, or even clean code, doesn't directly translate to return on investment. It may be nice to have consistent naming schemes, but is it worth the time developing and enforcing the scheme across 100s of developers?
  4. Laziness, incompetence, or Friday nights.

How can I tell when a CSS background image has loaded? Is an event fired?

8 votes

I have a sidebar widget that has an image background.

Over this is a search input form. I don't want the input to show before the image has loaded.

Is there a way to attach an load event handler to CSS background images like normal img elements/objects?

I know this could be done on a normal image, but I'd like to keep it as a CSS background because the image is part of a sprite. I am using jQuery, so solutions using jQuery or plain DOM JS are equally good.

You could load the same image using the DOM / a hidden image and bind to the load event on that. The browser's caching should take care of not loading the image twice, and if the image is already loaded the event should fire immediately... not tested, tough.