Best javascript questions in January 2011

Why does Internet Explorer not send HTTP post body on Ajax call after failure?

44 votes

We are able to reliably recreate the following scenario:

  1. Create a small HTML page that makes AJAX requests to a server (using HTTP POST)
  2. Disconnect from the network and reconnect
  3. Monitor the packets that IE generates after the failure

After a failed network connection, IE makes the next AJAX request but only sends the HTTP header (not the body) when doing the HTTP post. This causes all sorts of problems on the server as it is only a partial request. Google this issue with Bing and you'll find lots of people complaining about "random server errors" using AJAX or unexplained AJAX failures.

We know that IE (unlike most other browsers) always sends an HTTP POST as TWO TCP/IP packets. The header and body is sent separately. In the case directly after a failure, IE only sends the header.

So my question is - why does it behave this way? It seems wrong based on the HTTP spec and other browsers don't behave this way. Is it simply a bug? Surely this creates havoc in any serious AJAX based Web application.

Reference information:

There is a similar problem, triggered by HTTP keep-alive timeouts that are shorter than 1 minute and is documented here:

http://us.generation-nt.com/xmlhttprequest-post-sometimes-fails-when-server-using-keep-aliv-help-188813541.html

http://support.microsoft.com/default.aspx?kbid=831167

Here are the before and after failure packet captures:

Notice how the HTTP Header and Payload is sent http://img827.imageshack.us/i/beforee.png/

After a failure, notice how only the Header is sent. IE never sends the payload and the server eventually responds with a Timeout. http://img203.imageshack.us/i/retryt.png/

There does not seem to be a clear answer to this question, so I will provide my empirical data as a substitute and provide some ways to work around it. Maybe some MS insider will one day shed some light on this...

  1. If HTTP Keep-Alive is disabled on the server, this issue goes away. In other words, your HTTP 1.1 server server will respond to every Ajax request with a Connection: Close line in the response. This keeps IE happy but causes every Ajax request to open a new connection. This can have a significant performance impact, especially on high latency networks.

  2. The issue is triggered easily if Ajax requests are made in rapid succession. For example, we make Ajax requests every 100ms and then the network status changes, the error is easy to reproduce. Although most applications probably do not make such requests, you might well have a couple of server calls happening right after each other which could lead to this problem. Less chatty keeps IE happy.

  3. It happens even without NTLM authentication.

  4. It happens when your HTTP keep-alive timeout on the server is shorter than the default (which defaults to 60 seconds on Windows). Details provided in link in question.

  5. It does not happen with Chrome or Firefox. FF sends one packet so seems to avoid this issue altogether.

  6. It happens in IE 6, 7, 8. Could not reproduce with IE 9 beta.

When to use Vanilla Javascript vs. jQuery?

39 votes

I have noticed while monitoring/attempting to answer common jQuery questions, that there are certain practices using javascript, instead of jQuery, that actually enable you to write less and do ... well the same amount. And may also yield performance benefits.

A specific example

$(this) vs this

Inside a click event referencing the clicked objects id

jQuery

$(this).attr("id");

Javascript

this.id;

Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code)

EDIT : While I appreciate the answers regarding jQuery vs. plain javascript performance, I am actually looking for much more quantitative answers. While using jQuery, instances where one would actually be better off (readability/compactness) to use plain javascript instead of using $(). In addition to the example I gave in my original question.

  • this.id (as you know)
  • this.value (on most input types. only issues I know are IE when a <select> doesn't have value properties set on its <option> elements, or radio inputs in Safari.)
  • this.className to get or set an entire "class" property
  • this.selectedIndex against a <select> to get the selected index
  • this.options against a <select> to get a list of <option> elements
  • this.text against an <option> to get its text content
  • this.rows against a <table> to get a collection of <tr> elements
  • this.cells against a <tr> to get its cells (td & th)
  • this.parentNode to get a direct parent
  • this.checked to get the checked state of a checkbox Thanks @Tim Down
  • this.selected to get the selected state of an option Thanks @Tim Down
  • this.disabled to get the disabled state of an input Thanks @Tim Down
  • this.readOnly to get the readOnly state of an input Thanks @Tim Down
  • this.href against an <a> element to get its href
  • this.hostname against an <a> element to get the domain of its href
  • this.pathname against an <a> element to get the path of its href
  • this.search against an <a> element to get the querystring of its href
  • this.src against an element where it is valid to have a src

...I think you get the idea.

There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery.

In general you can replace:

$(el).attr('someName');

with:

Above was poorly worded. getAttribute is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute will set it. Necessary in some cases.

The sentences below sort of covered it. See this answer for a better treatment.

el.getAttribute('someName');

...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute too.

Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery:

$('span').unwrap();  // unwrap all span elements

But if there are many, you may want to do a little native DOM API:

var spans = document.getElementsByTagName('span');

while( spans[0] ) {
    var parent = spans[0].parentNode;
    while( spans[0].firstChild ) {
        parent.insertBefore( spans[0].firstChild, spans[0]);
    }
    parent.removeChild( spans[0] );
}

This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library.

It may seem like I have an infinite loop with the outer while because of while(span[0]), but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]);. This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.

Node.js, Cygwin and Socket.io walk into a bar... Node.js throws ENOBUFS and everyone dies...

37 votes

I'm hoping someone here can help me out, I'm not having much luck figuring this out myself. I'm running node.js version 0.3.1 on Cygwin. I'm using Connect and Socket.io. I seem to be having some random problems with DNS or something, I haven't quite figured it out. The end result is that I the server is running fine, but when a browser attempts to connect to it the initial HTTP Request works, Socket.io connects, and then the server dies (output below).

I don't think it has anything to do with the HTTP request because the server gets a lot data posted to it, and it was receiving requests and responding up until my connection that killed it. I've googled around and the closest thing I've found is DNS being set improperly. It's a network program meant to run only on an internal network, so I've set the nameserver x.x.x.x in my /etc/resolv.conf to the internal DNS. I've also added nameserver 8.8.8.8 in addition. I'm not sure what else to check, but would be grateful of any help.

In node.exe.stackdump

Exception: STATUS_ACCESS_VIOLATION at eip=610C51B9
eax=00000000 ebx=00000001 ecx=00000000 edx=00000308 esi=00000000 edi=010FCCB0
ebp=010FCAEC esp=010FCAC4 program=\\?\E:\cygwin\usr\local\bin\node.exe, pid 3296, thread unknown (0xBEC)
cs=0023 ds=002B es=002B fs=0053 gs=002B ss=002B
Stack trace:
Frame     Function  Args
010FCAEC  610C51B9  (00000000, 00000000, 00000000, 00000000)
010FCBFC  610C5B55  (00000000, 00000000, 00000000, 00000000)
010FCCBC  610C693A  (FFFFFFFF, FFFFFFFF, 750334F3, FFFFFFFE)
010FCD0C  61027CB2  (00000002, F4B994D5, 010FCE64, 00000002)
010FCD98  76306B59  (00000002, 010FCDD4, 763069A4, 00000002)
End of stack trace

Node Output:

    node.js:50
    throw e; // process.nextTick error, or 'error' event on first tick
    ^
Error: ENOBUFS, No buffer space available
    at doConnect (net.js:642:19)
    at net.js:803:9
    at dns.js:166:30
    at IOWatcher.callback (dns.js:48:15)

EDIT

I'm hitting an LDAP server using http.createClient immediately after a client connects to get information, and that seems to be where the problem is that is causing ENOBUFS. I've edited the source to include && errno != ENOBUFS which now prevents the server from dying, however now the LDAP request isn't working. I'm not sure what the problem is that would cause that though. As I mentioned this is an internal only application, so I set the DNS servers in /etc/resolv.conf to the DNS servers that are being applied to the host machine. Not sure if this is part of the issue?

EDIT 2

Here's some output from gdb --args ./node_g --debug ../myscript.js. I'm not sure if this is related to ENOBUFS, however, as it seems to be disconnecting immediately after connection with Socket.io

    [New thread 672.0x100]
Error: dll starting at 0x76e30000 not found.
Error: dll starting at 0x76250000 not found.
Error: dll starting at 0x76e30000 not found.
Error: dll starting at 0x76f50000 not found.
[New thread 672.0xc90]
[New thread 672.0x448]
debugger listening on port 5858
[New thread 672.0xbf4]
14 Jan 18:48:57 - socket.io ready - accepting connections
[New thread 672.0xed4]
[New thread 672.0xd68]
[New thread 672.0x1244]
[New thread 672.0xf14]
14 Jan 18:49:02 - Initializing client with transport "websocket"
assertion "b[1] == 0" failed: file "../src/node.cc", line 933, function: ssize_t
 node::DecodeWrite(char*, size_t, v8::Handle<v8::Value>, node::encoding)

Program received signal SIGABRT, Aborted.
0x7724f861 in ntdll!RtlUpdateClonedSRWLock ()
   from /cygdrive/c/Windows/system32/ntdll.dll
(gdb) backtrace
#0  0x7724f861 in ntdll!RtlUpdateClonedSRWLock ()
   from /cygdrive/c/Windows/system32/ntdll.dll
#1  0x7724f861 in ntdll!RtlUpdateClonedSRWLock ()
   from /cygdrive/c/Windows/system32/ntdll.dll
#2  0x75030816 in WaitForSingleObjectEx ()
   from /cygdrive/c/Windows/syswow64/KernelBase.dll
#3  0x0000035c in ?? ()
#4  0x00000000 in ?? ()
(gdb)

OK, I digged around a bit, and after your second edit I found this bug on the issue list.

I doesn't state whether this was encountered under cygwin or not, but the error that it is hitting leads down to this piece of code:

  uint16_t * twobytebuf = new uint16_t[buflen];

  str->Write(twobytebuf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);

  for (size_t i = 0; i < buflen; i++) {
    unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
    assert(b[1] == 0); // this assertion fails
    buf[i] = b[0];
  }

From what I can read (with my rusted C) it will convert it will create a new uin16 array and write the contents of the V8 string in their, then it will ensure that casting did not write any values outside the range of 0 - 255, and that's exactly what fails here.

I couldn't find anything regarding whether this is a V8 issue or not.

Since the code was added in this commit, the only thing I can suggest here is to try pulling the tree from a commit before the code was added. Since all versions after that have the crashing code.

If that works, I would recommend you to file another bug report on the issue Node.js issue list, although I made do this later this day.

Most appropriate way to get this: $($(".answer")[0])

27 votes

Suppose I want to get the first element amongst all the elements of the class ".answer"

$($(".answer")[0])

I can do the above, but what is the best balance between elegance and speed?

*changed the question to reflect the current discussion

The following are all equivalent in functionality (though not speed):

Which is the best?
It has been hypothesized that the selector versions should be faster than the method versions (and the logic makes some sense) but I have not yet found a reliable cross-browser, multi-document benchmark that proves this to be true.

And in some cases you cannot use the selector, as you have a jQuery object resulting from chained results and must later pare it down.

Edit: Based on the excellent information from @yc's tests below, following are the current (2011-Feb-4) test results summarized and compared against a baseline of .answer:first:

          :first  :eq(0)  .first()  .eq(0)  $($('...')[0])
Chrome 8+   100%     92%      224%    266%       367%
   FF 3.6   100%    100%      277%    270%       309%
  FF 4.0b   100%    103%      537%    521%       643%
 Safari 5   100%     93%      349%    352%       467%
 Opera 11   100%    103%      373%    374%       465%
     IE 8   100%    101%     1130%   1246%      1767%
 iPhone 4   100%     95%      269%    316%       403%
=====================================================
 Weighted   100%     92%      286%    295%       405%
    Major   100%     95%      258%    280%       366%
  • The Weighted line shows the performance weighted by the number of tests per browser; popular browsers (among those testing) are counted more strongly.
  • The Major line shows the same, only including non-beta releases of the major desktop browsers.

In summary: the hypothesis is (currently) wrong. The methods are significantly faster than the Sizzle selectors, and with almost exception the OP's code $($('.answer')[0]) is the fastest of them all!

Best JavaScript solution for client-side form validation and interaction?

18 votes

Our web forms are really complex. What's a great solution for extensible form validation, preferably one that works with jQuery?

Background:

Our site has a bit of Ajax, but the real focus is on user experience through about 20 multi-page forms or "wizards." These forms are complicated.

  • Presentation: Some fields are floats or ints. Validation means stripping non-decimal characters, but we also want to make sure that, if a user enters 5 into a price field, the field is updated to 5.00.
  • Side effects: Some fields have side effects when updated. E.g., updating the price or quantity of an item needs to update a subtotal field.
  • Widget-driven elements: Some fields are hidden and have values populated by widgets. E.g., a map widget lets you point to a location and a hidden field is updated with latitude-longitude coordinates, but the location must be within a certain region.
  • Groups: Some fields are groups, like address/city/state/zip, and should only be validated when all of the fields have bee populated.
  • Server-side validation: Validation of some fields requires back-end checking via Ajax requests
  • Multiple forms per page: Sometimes a user needs to fill out one form before a dialog opens with another form. A framework has to be more versatile than binding to onSubmit — we sometimes post multiple forms in order from the same page using Ajax. (E.g., we let users sign up and create a widget in one swoop but, due to legacy systems, that flow requires two POST requests.)
  • Customizable error display: Sometimes errors appear above fields, sometimes the field style changes, and our new designs call for tooltip-like popups (ala qTip) for some errors.
  • Snappiness: User experience is key and tactile feedback is important. Any solution
  • Submit buttons: Clicking the submit button needs to validate everything and then show a response — but since some of the validation happens asynchronously.

We're currently using the jQuery Validation library but our forms appear to be outgrowing its capability. I've been looking at things like <angular/>, Knockout and Backbone.js, but I'm worried that they're too heavyweight or that they would require us to rewrite our frontend.

(This should be a community wiki.)

Answering this myself since someone on our team noticed Validator from jQuery Tools !

  • Presentation - Supports HTML5 input fields. pattern fields make sure the user can only input test in a certain pattern.
  • Side effects - Triggers events on the form and on individual fields: onFail and onSuccess
  • Widget-driven elements - "Custom input types" are encouraged. The basic demo even includes a natural numbers-old "age" field.
  • Groups - Write a "function matcher" whose sole purpose is to filter which fields are to be validated.
  • Server-side validation - Does it and does it intelligently — depends on your validator calling a callback (so it's async-friendly) instead of a return value.
  • Multiple forms per page - jQuery Tools seems to be very well built and this shouldn't be a problem.
  • Customizable error display - Errors next to fields? All in one place? No problem. Still not good enough? Bind events on failure. Even uses tooltips by default.
  • Snappiness - Demos are very snappy
  • Submit buttons - No problem.

Update: Yep, just reimplemented a chunk of our site with jQuery Tools' validator tooltips. Fantastic!

In 2011 is it truly necessary to still degrade js?

16 votes

Serious question.

I tried most of the famous websites (including facebook) and I can say that tons of functionality doesn't degrade at all with js disabled. I've been always told that js should degrade gracefully, but does this still applies in these day and age?

ie6 support is being dropped by several sites, and most of the web2.0 relies heavily on js (especially ajax, I even found some sites that doesn't let you login without js enabled).

What are your thoughts about it?

EDIT:

I want to add that I for one develop webapps without js first and then enhancing them with it. The issue is that year after year js is more and more a part of the web. HTML5, canvas and heavy js apps are starting to rise. Will we ever reach the point where js will be compulsory in most of the websites? I talked about facebook because the site actually degrades and is usable without js but most of the functionalities and shortcuts are stripped to the poin that the site feels dull and old. There are also example where js is better than server side scripting, for instance the ordering of large tables is faster and less server intensive that a php implementation.

p.s. I don't know how to make this a community wiki, but I will, I'm just interested in your opinions.

In 2011 there are still several important types of users for whom you can't assume javascript will function properly:

  • search robots
  • browsers for visually impaired users
  • feature phones
  • corporate browsers, thin clients, etc still using IE6 or whatever
  • REST-based clients by fellow developers
  • your frontend usability testing tools
  • weird new browsers like my mom's Roku TV box

So I think it's still best to offer graceful degradation.

When to check for undefined and when to check for null

14 votes

[Bounty Edit]

I'm looking for a good explanation when you should set/use null or undefined and where you need to check for it. Basically what are common practices for these two and is really possible to treat them separately in generic maintainable coe?

[/Edit]

[Edit]

When can I safely check for === null, safely check for === undefined and when do I need to check for both with == null

[/Edit]

When should you use the keyword undefined and when should one use the keyword null

I have various checks in the format of

if (someObj == null) or if (someObj != null) which check for both null and undefined. I would like to change all these to either === undefined or === null but I'm not sure how to guarantee that it will only ever be one of the two but not both.

Where should you use checks for null and where should you use checks for undefined

A concrete example:

var List = []; // ordered list contains data at odd indexes.

var getObject = function(id) {
    for (var i = 0; i < List.length; i++) {
        if (List[i] == null) continue;
        if (id === List[i].getId()) {
            return List[i];
        }
    }
    return null;
}

var deleteObject = function(id) {
    var index = getIndex(id) // pretty obvouis function
    // List[index] = null; // should I set it to null?
    delete List[index]; // should I set it to undefined?
}

This is just one example of where I can use both null or undefined and I don't know which is correct.

Are there any cases where you must check for both null and undefined because you have no choice?

Functions implicitly return undefined. Undefined keys in arrays are undefined. Undefined attributes in objects are undefined.

function foo () {

};

var bar = [];
var baz = {};

//foo() === undefined && bar[100] === undefined && baz.something === undefined

document.getElementById returns null if no elements are found.

var el = document.getElementById("foo");

// el === null || el instanceof HTMLElement

You should never have to check for undefined or null (unless you're aggregating data from both a source that may return null, and a source which may return undefined).

I recommend you avoid null; use undefined.

JavaScript: Invert color on all elements of a page

13 votes

I want to be able to invert the color of all the elements on a page with a JavaScript bookmarklet. I know that to invert a color you subtract each of the RGB hex values from 255(xFF), but beyond that I am unsure of how to proceed.

How can I accomplish this?

Using jQuery is acceptable, and it only needs to work on Chrome, although if it worked in Firefox that'd be a plus.

EDIT: This is excluding images - background, text and links colors should all be inverted. Basically anything that gets its color from CSS.

UPDATE Here is an updated bookmarklet that fixes the nested element issue and will work on a lot of different sites (including this one):

javascript: function load_script(src, callback) {    var s = document.createElement('script');    s.src = src;    s.onload = callback;    document.getElementsByTagName('head')[0].appendChild(s);}function invertElement() {    var colorProperties = ['color', 'background-color'];    var color = null;    for (var prop in colorProperties) {        prop = colorProperties[prop];        if (!$(this).css(prop)) continue;        if ($(this).data(prop) != $(this).css(prop)) continue;        color = new RGBColor($(this).css(prop));        if (color.ok) {            $(this).css(prop, 'rgb(' + (255 - color.r) + ',' + (255 - color.g) + ',' + (255 - color.b) + ')');        }        color = null;    }}function invertColors() {    $('body').find('*').andSelf().each(function(){        var colorProperties = ['color', 'background-color'];        for (var prop in colorProperties){           prop = colorProperties[prop];    console.log(prop,$(this),$(this).data(prop),$(this).css(prop));            $(this).data(prop,$(this).css(prop));        }    });    $('body').find('*').andSelf().each(invertElement);    $('iframe').each(function () {        $(this).contents().find('*').each(invertElement);    });}load_script('http://www.phpied.com/files/rgbcolor/rgbcolor.js', function () {    if (!window.jQuery) load_script('https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', invertColors);    else invertColors();});

Still needs work on a number of different sites.

First things first, grab the awesome RGBColor class here.

Here goes:

jsFiddle example

//set up color properties to iterate through
var colorProperties = ['color', 'background-color'];

//iterate through every element
$('*').each(function() {
    var color = null;

    for (var prop in colorProperties) {
        prop = colorProperties[prop];

        //if we can't find this property or it's null, continue
        if (!$(this).css(prop)) continue; 

        //create RGBColor object
        color = new RGBColor($(this).css(prop));

        if (color.ok) { 
            //good to go, let's build up this RGB baby!
            //subtract each color component from 255
            $(this).css(prop, 'rgb(' + (255 - color.r) + ', ' + (255 - color.g) + ', ' + (255 - color.b) + ')');
        }
        color = null; //some cleanup
    }
});

Screenshot:

alt text

EDIT: Here's a bookmarklet you can now copy-paste into your browser (http://jsfiddle.net/F7HqS/1/)

javascript:function load_script(src,callback){var s=document.createElement('script');s.src=src;s.onload=callback;document.getElementsByTagName('head')[0].appendChild(s);}function invertColors(){var colorProperties=['color','background-color'];$('*').each(function(){var color=null;for(var prop in colorProperties){prop=colorProperties[prop];if(!$(this).css(prop))continue;color=new RGBColor($(this).css(prop));if(color.ok){$(this).css(prop,'rgb('+(255-color.r)+','+(255-color.g)+','+(255-color.b)+')');}color=null;}});}load_script('http://www.phpied.com/files/rgbcolor/rgbcolor.js',function(){if(!window.jQuery)load_script('https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',invertColors);else invertColors();});

Is parsing JSON faster than parsing XML

12 votes

I'm creating a sophisticated JavaScript library for working with my company's server side framework.

The server side framework encodes its data to a simple XML format. There's no fancy namespacing or anything like that.

Ideally I'd like to parse all of the data in the browser as JSON. However, if I do this I need to rewrite some of the server side code to also spit out JSON. This is a pain because we have public APIs that I can't easily change.

What I'm really concerned about here is performance in the browser of parsing JSON versus XML. Is there really a big difference to be concerned about? Or should I exclusively go for JSON? Does anyone have any experience or benchmarks in the performance difference between the two?

I realize that most modern web developers would probably opt for JSON and I can see why. However, I really am just interested in performance. If there's a proven massive difference then I'm prepared to spend the extra effort in generating JSON server side for the client.

JSON should be faster since it's JS Object Notation, which means it can be recognized natively by JavaScript. In PHP on the GET side of things, I will often do something like this:

<script type="text/javascript">
    var data = <?php json_encode($data)?>;
</script>

For more information on this, see here:

Why is Everyone Choosing JSON Over XML for jQuery?

Also...what "extra effort" do you really have to put into "generating" JSON? Surely you can't be saying that you'll be manually building the JSON string? Almost every modern server-side language has libraries that convert native variables into JSON strings. For example, PHP's core json_encode function converts an associative array like this:

$data = array('test'=>'val', 'foo'=>'bar');

into

{"test": "val", "foo": "bar"}

Which is simply a JavaScript object (since there are no associative arrays (strictly speaking) in JS).

Can someone explain this 'double negative' trick?

12 votes

Hello, I am by no means an expert at javascript, but I have been reading Mark Pilgrim's "Dive into HTML5" webpage and he mentioned something that I would like a better understanding of.

He states:

"Finally, you use the double-negative trick to force the result to a Boolean value (true or false)."

function supports_canvas() {
  return !!document.createElement('canvas').getContext;
}

If anyone can explain this a little better I would appreciate it!

A logical NOT operator ! converts a value to a boolean that is the opposite of its logical value.

The second ! converts the previous boolean result back to the boolean representation of its original logical value.

From these docs for the Logical NOT operator:

Returns false if its single operand can be converted to true; otherwise, returns true.

So if getContext gives you a "falsey" value, the !! will make it return the boolean value false. Otherwise it will return true.

The "falsey" values are:

  • false
  • NaN
  • undefined
  • null
  • "" (empty string)
  • 0

Which scripting language is better for embedding in multi-threaded C/C++ application

12 votes

Considering the following requirementes:

  • Must be supported on Windows. Preferably works also on other platforms.
  • Must support multi threading. By that I mean that the engine can work in parallel in multiple threads.
  • Readability is important.
  • License must be compatible with closed-source projects.

I like Python for its readablity. I am also have more experience with Python than other scripting languages. However CPython is not multi-threaded, and IronPython requires hosting the CLR and a compatible language (C++/CLI or C#).

You might consider embedding a popular JavaScript engine. Not only will they be fast and well-supported, but so many people know how to program in JavaScript that it will be easily adopted and read by a large audience.

According to this answer the SpiderMonkey engine is thread-safe, while Google/Chrome's V8 may not be.

Can I use CoffeeScript instead of JS for node.js?

10 votes

What are my restrictions if I want to code node.js and use CoffeeScript? Can I do anything I'd be able to do in JS?

Thanks

Yes, CoffeeScript simply compiles into pure JS, making it completely compatible with node.js.

To run CoffeeScripts on node, you can either:

  • Type coffee -c example.coffee to compile, followed by node example.js to run the compiled JS.
  • Simply type coffee example.coffee

Iterating Through N Level Children

10 votes

This seems like something neat that might be "built into" jQuery but I think it's still worth asking.

I have a problem where that can easily be solved by iterating through all the children of a element. I've recently discovered I need to account for the cases where I would need to do a level or two deeper than the "1 level" (just calling .children() once) I am currently doing.

jQuery.each(divToLookAt.children(), function(index, element)
    {
        //do stuff
    }
    );  

This is what I'm current doing. To go a second layer deep, I run another loop after doing stuff code for each element.

jQuery.each(divToLookAt.children(), function(index, element)
{
     //do stuff
    jQuery.each(jQuery(element).children(), function(indexLevelTwo, elementLevelTwo)
    {
        //do stuff
    }
    );  
}
);

If I want to go yet another level deep, I have to do this all over again.

This is clearly not good. I'd love to declare a "level" variable and then have it all take care of. Anyone have any ideas for a clean efficient jQueryish solution?

Thanks!

This is an awesome question because of the levels deep catch. Check out the fiddle.

Converted this to a plugin.

Activate

$('#div').goDeep(3, function(deep){ // $.fn.goDeep(levels, callback)
    // do stuff on `this`
});

Plugin

$.fn.goDeep = function(levels, func){
    var iterateChildren = function(current, levelsDeep){
        func.call(current, levelsDeep);

        if(levelsDeep > 0)
            $.each(current.children(), function(index, element){
                iterateChildren($(element), levelsDeep-1);
            });
    };

    return this.each(function(){
        iterateChildren($(this), levels);
    });
};

Recommended JavaScript annotated source code for learning.

10 votes

I have recently found annotated source code for underscore.js and backbone.js

I'm currently going through these reading them to learn how other authors structure and write javascript code. It's a good learning experience.

Can anyone recommend other high quality annotated source code that is worthwhile to read so that I can gain a better understanding of javascript and associated techniques.

Having finished reading underscore.js I would recommend the reading of their OOP wrapper

It's not quite "annotated code," but DailyJS has a huge series of articles called Let's Make a Framework.

10 votes

404 Page or 500 Page

Anyone have any idea how to do this sort of thing? The animation that moves with your mouse? Thanks for the correction, @Alin. Just a link to a tutorial would be nice.

EDIT: Just also learned it's the parallax effect. That should help.

The effect is accomplished with javascript, not just CSS.

The source code is on the page you linked to.

Have a look at jParallax, which makes it easy to implement the effect in a robust way on your own site: http://webdev.stephband.info/parallax.html

How to make this JavaScript much faster?

9 votes

Still trying to answer this question, and I think I finally found a solution, but it runs too slow.

var $div = $('<div>')
    .css({ 'border': '1px solid red', 'position': 'absolute', 'z-index': '65535' })
    .appendTo('body');

$('body *').live('mousemove', function(e) {
    var topElement = null;
    $('body *').each(function() {
        if(this == $div[0]) return true;
        var $elem = $(this);
        var pos = $elem.offset();
        var width = $elem.width();
        var height = $elem.height();
        if(e.pageX > pos.left && e.pageY > pos.top
            && e.pageX < (pos.left + width) && e.pageY < (pos.top + height)) {
            var zIndex = document.defaultView.getComputedStyle(this, null).getPropertyValue('z-index');
            if(zIndex == 'auto') zIndex = $elem.parents().length;
            if(topElement == null || zIndex > topElement.zIndex) {
                topElement = {
                    'node': $elem,
                    'zIndex': zIndex
                };
            }

        }
    });
    if(topElement != null ) {
        var $elem = topElement.node;
        $div.offset($elem.offset()).width($elem.width()).height($elem.height());
    }
});

It basically loops through all the elements on the page and finds the top-most element beneath the cursor.

Is there maybe some way I could use a quad-tree or something and segment the page so the loop runs faster?

Is there maybe some way I could use a quad-tree or something and segment the page so the loop runs faster?

Just step back a bit, realize how small the problem is, and that the harder your try the more complicated answer you will use.

Now what you need to do is to create 4 elements for the highlighting. They will form an empty square, and so your mouse events are free to fire. This is similar to this overlay example I've made.

The difference is that you only need the four elements (no resize markers), and that the size and position of the 4 boxes are a bit different (to mimick the red border). Then you can use event.target in your event handler, because it gets the real topmost element by default.

Another approach is to hide the exra element, get elementFromPoint, calculate then put it back.

They're faster than light, I can tell you. Even Einstein would agree :)

1.) The easy & nice - [Demo1] (overlay or borders) FF needs v3.0+

var box = $("<div class='outer' />").css({
  display: "none", position: "absolute", 
  zIndex: 65000, background:"rgba(255, 0, 0, .3)"
}) .appendTo("body");

var last = +new Date;
$("body").mousemove(function(e){
    var offset, el = e.target;
    var now = +new Date;
    if (now-last < 25) 
      return;
    last = now;
    if (el === document.body) {
        box.hide(); 
        return;
    } else if (el.className === "outer") {
        box.hide();
        el = document.elementFromPoint(e.clientX, e.clientY);
    }
    el = $(el);
    offset = el.offset();
    box.css({
        width:  el.outerWidth()  - 1, 
        height: el.outerHeight() - 1, 
        left:   offset.left, 
        top:    offset.top 
    });
    box.show();   
});​

2.) The fast & robust - [Demo2] (only supports borders)

var box = new Overlay();

$("body").mouseover(function(e){
  var el = $(e.target);
  var offset = el.offset();
  box.render(el.outerWidth(), el.outerHeight(), offset.left, offset.top);
});​

/**
 * This object encapsulates the elements and actions of the overlay.
 */
function Overlay(width, height, left, top) {

    this.width = this.height = this.left = this.top = 0;

    // outer parent
    var outer = $("<div class='outer' />").appendTo("body");

    // red lines (boxes)
    var topbox    = $("<div />").css("height", 1).appendTo(outer);
    var bottombox = $("<div />").css("height", 1).appendTo(outer);  
    var leftbox   = $("<div />").css("width",  1).appendTo(outer);
    var rightbox  = $("<div />").css("width",  1).appendTo(outer);

    // don't count it as a real element
    outer.mouseover(function(){ 
        outer.hide(); 
    });    

    /**
     * Public interface
     */

    this.resize = function resize(width, height, left, top) {
      if (width != null)
        this.width = width;
      if (height != null)
        this.height = height;
      if (left != null)
        this.left = left;
      if (top != null)
        this.top = top;      
    };

    this.show = function show() {
       outer.show();
    };

    this.hide = function hide() {
       outer.hide();
    };     

    this.render = function render(width, height, left, top) {

        this.resize(width, height, left, top);

        topbox.css({
          top:   this.top,
          left:  this.left,
          width: this.width
        });
        bottombox.css({
          top:   this.top + this.height - 1,
          left:  this.left,
          width: this.width
        });
        leftbox.css({
          top:    this.top, 
          left:   this.left, 
          height: this.height
        });
        rightbox.css({
          top:    this.top, 
          left:   this.left + this.width - 1, 
          height: this.height  
        });

        this.show();
    };      

    // initial rendering [optional]
    // this.render(width, height, left, top);
}

Most efficient way to use selectors in jQuery?

9 votes

is it more efficient to use $('.active') or $('div.active') ? I have always avoided including "div" because it's extra text in the javascript file I don't want the user to have to download.

Older versions of IE will benefit from the inclusion of div because they don't support getElementsByClassName().

Because of that, every element on the page needs to be selected with:

document.getElementsByTagName('*');

...and manually tested to see if it has the active class.

If you include div, then it is able to narrow it down a bit, since it can do:

document.getElementsByTagName('div');

...then test only those elements.

When I say older versions, I mean IE6 and IE7 since IE8+ supports querySelectorAll.


EDIT:

Browser suppport:

Guides for dealing with Unicode in PHP5?

9 votes

Hey everybody. I'm developing a new site (php5/mySQL) and am looking to finally get on the Unicode bandwagon. I'll admit to knowing next to absolutely nothing about supporting Unicode at the moment, but I'm hoping to resolve that with your help.

After desperately flexing my tiny, pathetic excuses for Googlefu-muscles, and scouring over each page that looked promising to my Unicode-newbie eyes, I have come to the conclusion that, while not entirely supported, my precious language of choice (PHP for those that have forgotten) has made at least a half-assed attempt at managing the foreign beast (and from what else I see, succeeding?). I have also come to the conclusion that

<php header('Content-Type: text/html; charset=utf-8'); ?>

is a great place to start and that I should be looking into supporting UTF-8 since I have plenty of space on my (shared, for the moment) hosting.

However, I'm not sure what this strange functionality known as mb_* means or how to incorporate it into functions such as strlen() and . . . to be honest at this point I don't know what other functionality (that I can't live without) is affected.

So I've come to you SO-ites in search of enlightenment and possibly straightening out my confused (where Unicode is concerned!) brain. I really want to support it but I need serious help.

P.S.: Does Unicode affect mysql_real_escape_string() or any other XSS prevention/security measures? I need to stay on top of this as well!

Thanks ahead of time.

  • Adding Javascript into the mix, since I'll be using a mix of pure and jQuery and no knowing about Unicode support + this language. ;)

  1. Welcome onboard utf8 :)
  2. You should simply use mb_* functions in place of your traditional str* functions
  3. MySQL and its API has long and well been supporting utf8, the only requirement that you use encoding when saving data and connecting. google for 'SET NAMES utf8'
  4. Note the 'u' modifier for preg_* functions that tells them to use unicode mode.

get word click in paragraphs

8 votes

I have an HTML document with about 30,000 words in it.

I'd like to be able to do something when a user clicks any word. For simplicity/concept right now, I'd just like to alert() that word.

For example, in the paragraph about, if I were to click on "have" it should run alert("have").

I'm using jQuery.

var p = $('p');

p
 .html(function(index, oldHtml) {
    return oldHtml.replace(/\b(\w+?)\b/g, '<span class="word">$1</span>')
 })
 .click(function(event) { alert(event.target.innerHTML) });

I took Pablo Fernandez's suggestions into account.

See it on jsFiddle.

Update

So, will this be performant (e.g., it won't freeze up a slow user's browser?) Also, could you elaborate about how event.target works?

It may very well slow the performance of a page with 30,000 words. I'd argue that is excessive and probably would benefit from being paginated, but I don't know your exact circumstances.

event.target property holds the element that started the event - the event bubbles up / propagates to its parent, which then handles the event, so you don't have 30,000 events on separate span elements.

iPad css3 animation flickers after keyboard use

8 votes

I'm developing an app for the iPad using HTML5/CSS3. I'm not using any framework and am just using whatever is natively supported on the device. I have created some css3 animations to emulate the typical iOS sliding left or sliding right when navigating between screens. Here's an example of the slide left animation which is taking advantage of the iPad's CSS3 hardware acceleration: (the ipad is running 4.2).

/*************************************************
Slide Left
*************************************************/
.screen.slideleft{
 -webkit-animation-duration: 0.5s;
 -webkit-animation-timing-function: ease-in-out;
}
.screen.slideleft.outgoing{
 z-index: 50 !important;
 -webkit-animation-name: slideleft-outgoing;

}
.screen.slideleft.incoming{
 z-index: 100 !important;
 -webkit-animation-name: slideleft-incoming;
}
@-webkit-keyframes slideleft-outgoing{
 from { -webkit-transform: translate3d(0%,0,0); }
 to { -webkit-transform: translate3d(-100%,0,0); }
}
@-webkit-keyframes slideleft-incoming{
 from { -webkit-transform: translate3d(100%,0,0); }
 to { -webkit-transform: translate3d(0%,0,0); }
}

I also have this CSS which I've attempted to use to fix the flicker:

.incoming,
.outgoing{
 display: block !important;
 -webkit-backface-visibility: hidden;
}

This works great until the iPad keyboard is used. After which point all the animations flicker severely.

I've been looking for examples of an iPad HTML5 app that uses the keyboard and doesn't have flickers afterwards, but haven't turned up much. The jqTouch demos exhibit the same behavior on the iPad (although I know they were designed for the iPhone).

I've turned up a few posts/questions of similar questions but have never found a good answer. I've been through http://css3animator.com/2010/12/fight-the-flicker-making-your-css3-animation-bomb-proof/ and the articles linked there but haven't had any success.

Any other suggestions?

Update 1/13 @ 9am

I've added this css and it helped a lot:

.incoming *,
.outgoing *{
 -webkit-backface-visibility: hidden;
 -webkit-transform: translate3d(0,0,0); /* This helps with the flicker a lot. */
}

The foreground elements don't seem to flicker anymore, but the backgrounds still do. Still looking for some help or helpful resources on Mobile Safari's memory handling tactics.

Update 1/16 @ 11pm

Increasing the z-index as suggested by anonymous. Didn't seem to make a difference.

Update 1/17 @ 8:30am

I've posted a demo of the problem here.

The transitions between screens work great...until you tap/click inside one of the form fields. After the keyboard slides up and returns, all the transitions flicker. Go to the URL inside the iOS simulator or on an actual iPad to see what I'm talking about.

Ultimately, there really wasn't a fix for this issue. It seems like form elements in WebKit on the iPad cause problems with flickering.

My workaround was that on the onblur of each form element, I refreshed the page using hash tags to ensure it refreshed to the exact same state. It still caused a "flicker" while it was refreshing, but it did keep the screen from flickering throughout the rest of the app.