Best jquery questions in August 2010

XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin

25 votes

I'm developing a page that pulls images from Flickr and Panoramio via jQuery's AJAX support.

The Flickr side is working fine, but when I try to $.get(url, callback) from Panoramio, I see an error in Chrome's console:

XMLHttpRequest cannot load http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=processImages&minx=-30&miny=0&maxx=0&maxy=150. Origin null is not allowed by Access-Control-Allow-Origin.

If I query that URL from a browser directly it works fine. What is going on, and can I get around this? Am I composing my query incorrectly, or is this something that Panoramio does to hinder what I'm trying to do?

Google didn't turn up any useful matches on the error message.

EDIT

Here's some sample code that shows the problem:

$().ready(function(){ 
    var url = 'http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=processImages&minx=-30&miny=0&maxx=0&maxy=150';
    $.get(url, function(jsonp) {
        var processImages = function(data) {
            alert('ok');
        }
        eval(jsonp);
    });
});

You can run the example online.

EDIT 2

Thanks to Darin for his help with this. THE ABOVE CODE IS WRONG. Use this instead:

$().ready(function(){ 
    var url = 'http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=?';
    $.get(url, function(data) {
        // can use 'data' in here...
    });
});

For the record, as far as I can tell, you had two problems:

  1. You weren't passing a "jsonp" type specifier to your $.get, so it was using an ordinary XMLHttpRequest. However, your browser supported CORS (Cross-Origin Resource Sharing) to allow cross-domain XMLHttpRequest if the server OKed it. That's where the Access-Control-Allow-Origin header came in.

  2. I believe you mentioned you were running it from a file:// URL. There are two ways for CORS headers to signal that a cross-domain XHR is OK. One is to send Access-Control-Allow-Origin: * (which, if you were reaching Flickr via $.get, they must have been doing) while the other was to echo back the contents of the Origin header. However, file:// URLs produce a null Origin which can't be authorized via echo-back.

The first was solved in a roundabout way by Darin's suggestion to use $.getJSON. It does a little magic to change the request type from its default of "json" to "jsonp" if it sees the substring callback=? in the URL.

That solved the second by no longer trying to perform a CORS request from a file:// URL.

Why am I finding Javascript/jQuery so difficult to get right?

22 votes

My background is in C and I've picked up PHP, mySQL, HTML, CSS without too much issue.

But I'm finding Javascript/jQuery surprisingly difficult to get right. Very frustrating. Why?

  1. It seems to violate a number of traditional programming principles (e.g. variable scope)

  2. Undefined variables seem to appear out of nowhere and already have values associated with them. For example (from the jQuery docs):

    $("a").click(function(event) {
        event.preventDefault();
        $('<div/>')
              .append('default ' + event.type + ' prevented')
              .appendTo('#log');
    });
    

    What exactly is "event"? Do I have to use this variable name? Should I just assume that this object is magically instantiated with the right stuff and I can use any of the methods list at the JQuery API?

  3. There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)

  4. Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)

  5. Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.

It seems like everyday there's some random JS "rule" that comes up that I've never seen before in any of my JS books or tutorials.

What do I need to do to make Javascript/jQuery more deterministic, controlled, and logical to me?

Are there any resources that explain Javascript's quirks/gotchas?

Thanks!

Douglas Crockford's "Javascript: The Good Parts" was an invaluable resource. Javascript plays a lot more like Lua, Lisp, or Python than C, it just happens to LOOK like C.

Link provided to Amazon; I snagged mine from O'Reilly.

Graceful way to tell users of IE7 and below to go away?

22 votes

TLDR: Tell IE6/7 users to leave in a nice way :) whilst blocking them from all content.

Basically I do not need people using IE7/6 lower on my web app. Was thinking of just doing a doc.write after load to wipe the page with a message of "Sorry your browser is outdated" has anyone done similar and found a nice friendly way to tell them to come back with a better browser?

Am currently using jquery so jquery solutions viable.

(1) Most reliable way to detect browser?

(2) Opinion on what to present to the user?


The SCENARIO is not the question here

They will have access to upgrade if need be!

I have legit reasons for doing so so stay ontopic to the question and don't voice opinions about the general topic of IE6 and how much you love it.

Use an IE conditional statement (e.g. <![if lte IE 7]>Upgrade your browser<![endif]>) and remove the content with jQuery.

"javascript:void(0);" vs "return false" vs "preventDefault()"

18 votes


When I want some link to not do anything but only respond to javascript actions what's the best way to avoid the link scrolling to the top edge of the page ?
I know several ways of doing it, they all seem to work fine :

<a href="javascript:void(0)">Hello</a>

or

<a id="hello" href="#">Hello</a>
<script type="text/javascript>
  $(document).ready(function() {
    $("#toto").click(function(){
      //...
      return false;
    });
  });
</script>

and even :

<a id="hello" href="#">Hello</a>
<script type="text/javascript>
  $(document).ready(function() {
    $("#toto").click(function(event){
      event.preventDefault();          
      //...
    });
  });
</script>

Do you have any preference ? why ? in which conditions ?

PS: of course the above examples assume you're using jquery but there's equivalents for mootools or prototype.

Binding:

  • javascript: URLs are a horror to be avoided at all times;
  • inline event handler attributes aren't brilliant either, but OK for a bit of rapid development/testing;
  • binding from script, leaving the markup clean, is typically considered a best practice. jQuery encourages this, but there is no reason you can't do it in any library or plain JS.

Responses:

  • return false means both preventDefault and stopPropagation, so the meaning is different if you care about parent elements receiving the event notification;
  • jQuery is hiding it here but preventDefault/stopPropagation have to be spelled differently in IE usually (returnValue/cancelBubble).

However:

  • You have a link that isn't a link. It doesn't link anywhere; it's an action. <a> isn't really the ideal markup for this. It'll go wrong if someone tries to middle-click it, or add it to bookmarks, or any of the other affordances a link has.
  • For cases where it really does point to something, like when it opens/closes another element on the page, set the link to point to #thatelementsid and use unobtrusive scripting to grab the element ID from the link name. You can also sniff the location.hash on document load to open that element, so the link becomes useful in other contexts.
  • Otherwise, for something that is purely an action, it would be best to mark it up like one: <input type="button"> or <button type="button">. You can style it with CSS to look like a link instead of a button if want.
  • However there are some aspects of the button styling you can't quite get rid of in IE and Firefox. It's usually not significant, but if you really need absolute visual control a compromise is to use a <span> instead. You can add a tabindex property to make it keyboard-accessible in most browsers although this isn't really properly standardised. You can also detect keypresses like Space or Enter on it to activate. This is kind of unsatisfactory, but still quite popular (SO, for one, does it like this).
  • Another possibility is <input type="image">. This has the accessibility advantages of the button with full visual control, but only for pure image buttons.

How secure are CDNs for delivering jQuery?

17 votes

We build sites that have a public (non-secured) area and secured (delivered over HTTPS) area and we use jQuery library.

Recently I suggested we use Google CDN for jQuery delivery. Some of my colleagues expressed concerns in regards to security aspect of this way of delivering JavaScript libraries. For example, they mention the scenario where someone might hijack DNS server and then inject maliciously modified library, opening the door for different security attacks. Now, if hacker can inject malicious code through Google CDN, then he can probably do the same if jQuery is served from the site itself, right?

It seems that google CDN supports serving libraries over SSL.

Is serving jQuery from CDN really less secure then serving it from the server itself? How serious is this threat?

One way to mitigate the risk is to run a checksum against the file obtained from Google, and compare that to a known-good checksum already in your possession.

In response to a question about whether Google alters these files in any way, Google employee Ben Lisbakken suggested comparing MD5 checksums of a file provided by Google to the canonical version of that same file as obtained from its maintainers' home site. Read comment eight on the linked site for context.

If you're concerned about DNS hijacking, then of course the same concerns would apply to the file as obtained from the "original" site. You also probably don't want to incur the speed penalty of running a checksum against the jQuery file on every request -- unless you're incredibly paranoid. And of course, doing so would remove all advantages of using a CDN.

But assuming you're only somewhat paranoid, you could try something like this:

  • Make sure you're referencing a unique and specific version of the jQuery file from Google. For example, do this:

    http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
    

    and not this:

    http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js
    

    The latter version may return 1.4.2 now, but 1.4.3 tomorrow. If you have a combination of http and https needs, you can use protocol-relative URLs, like this:

    //ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
    
  • Initially generate and store your own checksum for this file.

  • Periodically repeat the process, and make sure the new checksum matches the old one. If it doesn't, sound the klaxons.

You can do this programmatically, of course. You decide what interval makes sense. Every minute? Every five? You now have the makings of an automatic kill-switch whose sensitivity you can adjust to your preference. The "monitor" routine certainly doesn't have to run synchronously within the application you're looking to secure; perhaps you run a small utility application on the same server just for this purpose.

It's easy enough to test: just alter the stored hash. Since you're referencing a specific file version, the panic button won't be pressed with every minor version update. When you do want to move to a new version of jQuery, change the AJAX API URL on your site and store the new hash.

javascript context menu click event/detection - filter paste content

15 votes

Scenario: I'm trying to intercept paste events inside a textarea/input text, and filter the content being pasted.

Webkit/IE are handled rather well, as I can attach code to the onpaste event, and then read from the clipboard what is being pasted. Plenty of examples around.

Gecko is trickier, because as far as I know it isn't possible to read the clipboard content on ffox (unless somebody knows a workaround for that?)
I just use the input swap trick for that.

Opera is being annoying tho. I can trap CTRL+V and SHIFT+INS, but there's no onpaste event.
Not to mention any sort of clipboard interaction, apparently.

So, my question is:

Can I detect if the user clicked on paste in the context menu on Opera? Is there any other way to detect the event?

EDIT:

Thanks everybody for the answers - they all add a good input, even if there's no definitive solution.
Having to choose, I'll pick the only one that tried to address the original question, and that would probably work if it wasn't too much of an hack to even try.

Notes for those that have my same problem (input filtering):

  • it is possible to capture content being dragged: mouseup + setTimeout does the trick everywhere almost perfectly.
  • without flash, there is probably no solution bar polling. Even with flash, it's not a completely solid solution either. Too much effort to support 100% of the cases.

I would like to point out DOJO menu widget that is creating context menus perfectly in different browsers. http://www.dojotoolkit.org/reference-guide/dijit/Menu.html#dijit-menu

What you can do is that detect paste event in browsers that are supporting it and override context menu in browsers that are not supporting this event like opera.

Once you create your own context menu then you can add copy paste menu item or create context menu similar to the default using css.

Edited Some browsers might not allow us to fetch clipboard content, in this case we can always revert back to flash for borrowing some of its features that are cross browser. See couple of links I posted in comments.

Its complete implementation might have more issues than anticipated but it is possible and we can always give it a try (I will for sure).

How does Stackoverflow's "Post Your Question" button stay disabled until question gets submitted?

12 votes

I am using asp.net webforms; I want to submit a form and keep the button disabled until it gets saved to my database, exactly like Stackoverflow. Any suggestion?

protected void Lb_Save_Click(object sender, EventArgs e)
{
   //disable my button
      //Do a DB insert 
   //enable my button
}

EDIT:

I'll do a client-side validation first so I don't want my button to be disabled there but I want to disable it once the onclick function starts. Hope you all get my point.

Also i would like to do the same for asp:linkbutton but i don't know how firefox behaves for it. As the linkbutton will be rendered as anchor how can i disable it?

Guys you didn't get my question.

How to disable asp:button during postback? (not in jQuery/Javascript)

It disables it on submit(), it never enables it again because you're redirected. However, if you wanted to do some sort of validation you would just do

$("#yourForm").submit(function(e) {
    $("#yourButton").attr('disabled','disabled');
    if (whateverValidation) {
        e.preventDefault();
        $("#yourButton").removeAttr('disabled');
    } 
});

Do "" and '' have different meanings in JavaScript?

10 votes

Possible Duplicate:
When to Use Double or Single Quotes in JavaScript

Hello,

Do "" and '' have different meanings in JavaScript? Because I keep seeing those two usages in Jquery, for instance.

$("")

and

$('')

Thanks for helping

No, they mean the same thing; they are both just JavaScript string literals. It is convenient to have two different quotes so you can nest them without having to use escape sequences; "some string with 'single quotes' in it" or 'a string with "double quotes" in it'.

What does $([]) mean in jQuery?

10 votes
var username = $("#username"),
                password = $("#password"),
                allFields = $([]).add(username).add(password);

What is allFields? What is $([])?

Being a newbie to Javascript/jQuery, I've never seen this $([]) notation before and I'm interested in its associated methods.

Given that its "$([])", it's tricky to search for. And a Google search of arrays in Javascript (guessing that thing is an array of some sort) yields the typical arrays I'm familiar seeing.

So what is $([])? Can anyone point me to some documentation? I'm interested in learning how to use this strange thing.

The jQuery function accepts an array of DOM nodes.

$([document.body]) for example which will return a jQuery object by wrapping all the DOM elements passed in that array. However, since in your example there is no DOM object to begin with and it's just an empty array, there is not need to even pass an empty array.

Calling the jQuery function without any arguments returns an empty set. Taken from jQuery docs,

Returning an Empty Set

As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.

So, your example would work the same if you had instead called

$().add(username).add(password);

As other answers have mentioned and the docs say, passing an empty array was required before v 1.4.

2 part CSS "wallpaper" that resizes to browser

10 votes

My designer believes this cannot be done, however it seems possible to me. (Although I have limited CSS experience). However, he also said the background couldn't be fixed, and stackoverflow has proved his wrong in the past; so I question his knowledge.

JQuery can be used if this cannot be done in pure CSS. alt text

The top half will be a gradient that has full flexible to skew left, right, up, down without much distortion. The bottom half is an image that is ideally made for the 1280 x 1024 resolution (as this is the most popular browser display resolution). Then depending on the requirements needed it will sketch and skew to whatever size it needs. Still allowing all of the image to be seen.

The ration between the top half and bottom half is always 50% 50% independent of browser resolution.

I would also like if both the top and bottom parts are fixed.

In a perfect world (one without IE), id like to do this with css3 gradients and multiple backgrounds in 1 DIV. However, because IE9 isnt out yet, I think the best way to approach it would be 2 divs in a DIV container and using a PNG repeating background for the top div.

It should be noted I am going to use css3pie.com to allow some CSS3 for IE6-8 (but I dont want to rely on it, unless 100% proven)

Is this possible with just CSS? How would you do it?

If not possible with just CSS, is there a way I can get JavaScript/JQuery to aid? I am thinking a base of 1280 x 1024 isn't the best idea because it seems to have an odd radio.

Edit 1

Oh yeah, I have a WIP too: http://meyers.ipalaces.org/extra/

It looks good in 1280 x 1024...now its just getting the whole resizing of the top DIV to be 50% so the image is 50%.

I'd still like ALL of the water to be seen, because I like the look of the rocks at the bottom. However, I am open to alternative ideas that don't accomplish what I want 100%, but come close.

Edit 2

How about using the top gradient as the true CSS2 background and then just putting a <img> at the bottom of it to resize? Perhaps that will allow for CSS2 ability. I am reference some work-around techniques here: A list apart

Edit 3

I am still looking for results that work on IE6 and also don't cause Internet explorer to lag. I am setting a bounty of 50 to help attract more attention.

I have successfully came up with 2 ways to do this:

Method 1

Click here to view demo

Using CSS3 background-size I was able to set 2 div elements to on top of each other with min-height: 50% and then using background-size: 100% 50% they successfully accomplish what I am looking for.

This method was just a proof of concept, as IE6-8 does not support background-size, I didn't pursue tweaking this method perfectly. As it stands, it currently messes up when you scroll despite have background-attachment: fixed;. I ditched this CSS3 method in order to look for better methods using CSS tricks...


Method 2

Click here to view demo

Following the examples I found from A List Apart (Article | Example1 | Example2). I used Technique #2 from Example 1, and I was able to emulate what I wanted to do using just CSS2. (I am not 100% sure how or why this works, but it does)

Because I am also going to use CSS3PIE to give IE6-8 CSS3 the ability to do linear gradients, border-radius, and box-shadow; I opted to use a linear gradient instead of an image for the top background.

Problems

  • CSS2 Method from Technique #2, Example 1 does not work with IE6 Correctly
  • Creates excessive lag in all current Internet Explorers

JQuery Garbage Collection - Will This Be Clean?

9 votes

Many articles (e.g. msdn) have told be that a circular reference can not be cleaned up in some browsers when it involves a DOM object and a JS object.

(IE 6 can't do it at all and IE7 can only do it between page requests):

Javascript Native (Leaks):

function leak(){
    var elem = document.createElement("DIV");
    document.body.appendChild(elem);
    elem.onclick = function () {
        elem.innerHTML = elem.innerHTML + ".";
        // ...
    };
}

Because the element's onload property refers back to itself through a closure, it creates a circular reference:

elem [DOM] -> elem.onclick [JS] -> elem [DOM]

JQuery Version (Does NOT Leak):

function leak(){
    var elem = $('<div></div>');
    $(document.body).append(elem);
    elem.click(function () {
        elem.html(elem.html() + ".");
        // ...
    };
}

In this case, jQuery stops the leak from happening in ALL browsers concerned even though there is still a circular reference:

elem [JS] -> element [DOM] -> elem.onclick [JS] -> elem [JS]

My Question: How does jQuery stop the leak if there is still a circular reference?

The very last thing in the jQuery code (before the code for Sizzle, it's selector engine) is this - which is the code to prevent the leaks:

// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
//  - http://isaacschlueter.com/2006/10/msie-memory-leaks/
if ( window.attachEvent && !window.addEventListener ) {
    window.attachEvent("onunload", function() {
        for ( var id in jQuery.cache ) {
            if ( jQuery.cache[ id ].handle ) {
                // Try/Catch is to handle iframes being unloaded, see #4280
                try {
                    jQuery.event.remove( jQuery.cache[ id ].handle.elem   );
                } catch(e) {}
            }
        }
    });
}

When you do anything in jQuery, it stores both what is has done (i.e. the function) and to what (i.e. the DOM element). onunload goes through the jQuery cache removing the functions from the event handlers of its own internal cache (which is where the events are stored anyway rather than on the individual DOM nodes).

Oh, and the line: if ( window.attachEvent && !window.addEventListener ) { ensures that it just runs on IE.

Is this a valid email address?

9 votes
"Françoise Lefèvre"@example.com

I'm reading RFC 5321 to try to actually understand what constitutes a valid email address -- and I'm probably making this a lot more difficult than it needs to be -- but this has been bugging me.

               i.e., within a quoted string, any
               ASCII graphic or space is permitted
               without blackslash-quoting except
               double-quote and the backslash itself.

Does this mean that ASCII extended character sets are valid within quotes? Or does that imply standard ASCII table only?

EDIT - With the answers in mind, here's a simple jQuery validator that could work in supplement to the the plugin's built-in email validation to check the characters.

jQuery.validator.addMethod("ascii_email", function( value, element ) { 
    // In compliance with RFC 5321, this allows all standard printing ASCII characters in quoted text.
    // Unquoted text must be ASCII-US alphanumeric or one of the following: ! # $ % & ' * + - / = ? ^ _ ` { | } ~   
    // @ and . get a free pass, as this is meant to be used together with the email validator

    var result = this.optional(element) || 
        (
            /^[\u002a\u002b\u003d\u003f\u0040\u0020-\u0027\u002d-u002f\u0030-\u0039\u0041-\u005a\u005e-\u007e]+$/.test(value.replace(/(["])(?:\\\1|.)*?\1/, "")) &&     
            /^[\u0020-\u007e]+$/.test(value.match(/(["])(?:\\\1|.)*?\1/, ""))   
        );
    return result;
}, "Invalid characters");

The plugin's built-in validation appears to be pretty good, except for catching invalid characters. Out of the test cases listed here it only disallows comments, folding whitespace and addresses lacking a TDL (ie: @localhost, @255.255.255.255) -- all of which I can easily live without.

According to this MSDN page the extended ASCII characters aren't valid, currently, but there is a proposed specification that would change this.

http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress(VS.90).aspx

The important part is here:

Thomas Lee is correct in that a quoted local part is valid in an email address and certain mail addresses may be invalid if not in a quoted string. However, the characters that others of you have mentioned such as the umlaut and the agave are not in the ASCII character set, they are extended ASCII. In RFC 2822 (and subsequent RFC's 5322 and 3696) the dtext specification (allowed in quoted local parts) only allows most ASCII values (RFC 2822, section 3.4.1) which includes values in ranges from 33-90 and 94-126. RFC 5335 has been proposed that would allow non-ascii characters in the addr-spec, however it is still labeled as experimental and as such is not supported in MailAddress.

When running user inputed Javascript, is there a way to detect and stop "problem" scripts?

9 votes

On a page, something like jsFiddle, that executes user inputed Javascript, is there a way to stop / disrupt "problem" scripts running in an iframe?

The major class of problem scripts would be infinite loops, I think. Browsers deal with multiple alerts quite well, but a script like, ​for (var i = 0; ++i; i < 100) { /* do stuff */ }​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ will go forever.

How can I either detect and not run, or run and stop, say after 10 seconds of running, a script?

Removing the iframe is fine, but I only want to remove it if the script is still running after 10 seconds, but I don't want to remove it if the script has stopped running.


Here is how I imagine the page will work. If you have a better solution, let me know...

The input page contains a textarea and a blank iframe. The user enters their script into the textarea, and when ready they click on run. Then (backstage) a separate page is created that contains the user script in executable form on an HTML page. The src of the iframe is set to the page with the executable code. This all happens dynamically without a page refresh.

I haven't used this jsandbox script, but it appears to have what you want.

jquery json to string?

9 votes

Instead of going from a json string and using $.parseJson, I need to take my object and store it in a variable as string representing json.

(A library I'm dealing with expects a malformed json type so I need to mess around with it to get it to work :( )

What's the best way to do this?

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

var tmp = {one: 1, two: "2"};
JSON.stringify(tmp); // '{"one":1,"two":"2"}'

Code from: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/

In Firebug, $ == jQuery returns false, only sometimes

9 votes

Okay, I have this weird problem in Firefox. I type in Firebug's console

$ == jQuery

Sometime it displays true, and sometimes false. The file is just an empty HTML document with one script tag including jQuery. I refresh the page, click "Run" in the console, and again, occasionally it returns true, occasionally false.

On the occasions where it returns false, $.toString() gives

function anonymous() {
    return window.console.notifyFirebug(arguments, "$", "firebugExecuteCommand");
}

Now here's the weird thing. When $ == jQuery gives false using Firebug's console, if I go to the address bar and type javascript:alert($ == jQuery);, it alerts true!

Does anyone have any idea what's going on here? It's (occasionally) messing up my debugging.

There's a native function defined by firebug that assigns $ to getElementById. I don't think you can resolve this "bug" without upgrading to a newer version of Firebug which potentially eliminated the issue, or manually assign $ = jQuery.

It's probably come as a result of possibly jQuery already being cached and the Firebug $ overriding it as it fires too fast, or vice versa.. just some weird bug in regards to speed of assignment + caching.

RightJS javascript library in daily use.

9 votes

Wondering if anyone here can offer any insight into the ups/downs of using the RightJS library, specifically as compared to jQuery, and generally compared to what you think a library ought to offer.

I'm not so much looking for a feature to feature comparison, but rather a sense of the general daily use.

Things like:

  • Does it feel natural to use, or does it feel like an uphill battle?
  • Does the API express itself in a comprehensible manner, or do you find yourself wondering what the code you wrote 3 weeks ago means?
  • Do you find yourself wishing it had some feature of jQuery (or some feature in general), or inversely, do you enjoy some particular feature that other libraries don't have?
  • General philosophical considerations that you think make RightJS superior/inferior.

Not things like:

  • Mindshare/marketshare/plugins/CDN/ considerations (the winner is obvious)
  • Why would you bother... (moot)
  • jQuery does x, y and z, and RightJS doesn't, without offering insight into how it impacts daily use (there could be philosophical reasons that make x, y and z unnecessary)

Based on the documentation, code samples, and what is already in the works for RightJS 2, I am very impressed.

@Patrick - Thanks for pointing out the Call By Name feature in RightJS which seems extremely useful for removing most anonymous functions from all over the page. For those who are not familiar with it, the idea is to specify the method name and arguments as parameters instead of creating an anonymous callback. For example, if we are trying to filter all words and phrased that begin with "hello" from an array,

var words = ['stack', 'hello world', 'overflow', 'hello there'];

Using the filter method on arrays, we would write:

words.filter(function(word) {
    return word.indexOf('hello') === 0;
});

We can write the same thing using Call By Name in RightJS as,

words.filter('startsWith', 'hello');

Pretty sweet eh?

I am also loving the idea of being able to use strings as selectors directly. Although RightJS only does it for event delegation at the moment, but I would love to be able to completely get rid of the $ function for most purposes and directly call methods on a string. For example, to listen to all clicks on any para on the page, write:

'p'.on('click', function() {
    this.addClass('clicked');
});

Or maybe combine this with Call By Name,

'p'.on('click', 'addClass', 'clicked');

The things I am excited about in RightJS 2 is the ability to use widgets as native elements.

var calendar = new Calendar();

calendar instanceof Calendar; // true
calendar instanceof Element; // true

Thanks to @patrick and @Nikolay for clarifying my assumption here. The widget will wrap the native DOM element which is available as the _ property on the object.

document.body.appendChild(calendar._);

or use the methods provided by the framework.

calendar.insertTo(document.body)

Another nice feature is a unified way to initialize widgets using just a declarative syntax:

<input data-calendar="{format: 'US', hideOnClick: true}" />

instead of creating an object ourselves and then adding it to the page:

var calendar = new Calendar({
    format: 'US',
    hideOnClick: true
});

calendar.insertTo(document.body);

I have taken the slides from a presentation titled JavaScript Library Overview by John Resig and compared the code samples for jQuery with RightJS. These samples mainly compare the basic syntax for both frameworks which is more similar than different, although RightJS seems to be more flexible in its usage.

DOM Traversal

jQuery

$('div > p:nth-child(odd)')

RightJS

$$('div > p:nth-child(odd)')

DOM Modification

jQuery

$('#list').append('<li>An Item</li>')

RightJS

$('list').insert('<li>An Item</li>')

Events

jQuery

$('div').click(function() {
    alert('div clicked')'
});

RightJS

$$('div').onClick(function() {
    alert('div clicked');
});

AJAX

jQuery

$.get('test.html', function(html) {
    $('#results').html(html);
});

or

$('#results').load('test.html');

RightJS

Xhr.load('test.html', {
    onSuccess: function(request) {
        $('#results').html(request.text);
    }
}).send();

or

$('results').load('test.html');

Animations

jQuery

$('#menu').animate({ opacity: 1 }, 600);

RightJS

$('menu').morph({ opacity: 1 }, { duration: 600 });

Array traversal

jQuery

$.each(myArray, function(index, element) {
    console.log(element);
});

RightJS

myArray.each(function(element) {
    console.log(element);
});

What's the difference between jquery.js and jquery.min.js?

8 votes

What is the difference between jquery.min.js and jquery.js?

Which one has support for all functions?

Just to point out as well, you are better using the minified version (.min) for your live environment as Google are now checking on page loading times. Having all your JS file minified means they will load faster and will score you more brownie points.

You can get an addon for Mozilla called Page Speed that will look through your site and show you all the .JS files and provide minified versions (amongst other things).

How to represent mathematical symbols and capture user input for the same

8 votes
  1. How do you capture user input related to mathematical fractions. Assuming I would like to present a simple square and ask the user to select 3/4ths of a square. What kind of UI control should we use to first all represent a square (with 4 equal blocks inside) and to have a mechanism to capture user input.

  2. Assuming you would like to draw a scale which is 1 meter long and and you have markings for every 10 cm (e.g. 10, 20, 30 ...90, 100). We would like the user to plot 40 cm on the scale. What kind of UI controls are available which will help us in drawing such inputs and capturing student response.

Are there any tools or libraries which we can use to build such solutions? Our environment is based on (java, richfaces, jquery ...)

While it is possible to hack together HTML or jQuery controls to draw and detect clicks on rectangles, if you are going to draw your own graphics with fonts, symbols, scale and rotation, you are eventually going to have to move to a graphics API. I suggest using the HTML5 Canvas element.

Canvas is the W3C-approved method for adding interactive graphics to web pages and is supported by all modern browsers, including IE with a plug-in.

A free chapter from Dive into HTML5 shows how to create a playable HTML5 game using only JavaScript in a Canvas element.

jQuery DataTables server-side processing using ASP.NET WebForms

8 votes

Problem:

  • jQuery DataTables server-side processing using ASP.NET WebForms.

Solution:

  • Darin Dimitrov answered the question using an example which pages and sorts, but doesn't do any searching. Here's my **basic** modification of his work to make searching work on his example:
public class Data : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Paging parameters:
        var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
        var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);

        // Sorting parameters
        var iSortCol = int.Parse(context.Request["iSortCol_0"]);
        var iSortDir = context.Request["sSortDir_0"];

        // Search parameters
        var sSearch = context.Request["sSearch"];

        // Fetch the data from a repository (in my case in-memory)
        var persons = Person.GetPersons();

        // Define an order function based on the iSortCol parameter
        Func<Person, object> order = person => iSortCol == 0 ? (object) person.Id : person.Name;

        // Define the order direction based on the iSortDir parameter
        persons = "desc" == iSortDir ? persons.OrderByDescending(order) : persons.OrderBy(order);

        // prepare an anonymous object for JSON serialization
        var result = new
                         {
                             iTotalRecords = persons.Count(),
                             iTotalDisplayRecords = persons.Count(),
                             aaData = persons
                                 .Where(p => p.Name.Contains(sSearch))  // Search: Avoid Contains() in production
                                 .Where(p => p.Id.ToString().Contains(sSearch))
                                 .Select(p => new[] {p.Id.ToString(), p.Name})
                                 .Skip(iDisplayStart)   // Paging
                                 .Take(iDisplayLength)
                         };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(result);
        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }

    public bool IsReusable { get { return false; } }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static IEnumerable<Person> GetPersons()
    {
        for (int i = 0; i < 57; i++)
        {
            yield return new Person { Id = i, Name = "name " + i };
        }
    }
}

I wrote a simple example that should illustrate the idea.

Start by writing a generic handler for handling data on the server side (Data.ashx but this could be a web page, web service, anything server side script capable of returning JSON formated data):

public class Data : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Those parameters are sent by the plugin
        var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
        var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);
        var iSortCol = int.Parse(context.Request["iSortCol_0"]);
        var iSortDir = context.Request["sSortDir_0"];

        // Fetch the data from a repository (in my case in-memory)
        var persons = Person.GetPersons();

        // Define an order function based on the iSortCol parameter
        Func<Person, object> order = p => 
        {
            if (iSortCol == 0) 
            { 
                return p.Id; 
            }
            return p.Name;
        };

        // Define the order direction based on the iSortDir parameter
        if ("desc" == iSortDir)
        {
            persons = persons.OrderByDescending(order);
        }
        else
        {
            persons = persons.OrderBy(order);
        }

        // prepare an anonymous object for JSON serialization
        var result = new
        {
            iTotalRecords = persons.Count(),
            iTotalDisplayRecords = persons.Count(),
            aaData = persons
                .Select(p => new[] { p.Id.ToString(), p.Name })
                .Skip(iDisplayStart)
                .Take(iDisplayLength)
        };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(result);
        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static IEnumerable<Person> GetPersons()
    {
        for (int i = 0; i < 57; i++)
        {
            yield return new Person
            {
                Id = i,
                Name = "name " + i
            };
        }
    }
}

And then a WebForm:

<%@ Page Title="Home Page" Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title></title>
    <link rel="stylesheet" type="text/css" href="/styles/demo_table.css" /> 
    <script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="/scripts/jquery.dataTables.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#example').dataTable({
                'bProcessing': true,
                'bServerSide': true,
                'sAjaxSource': '/data.ashx'
            });
        });
    </script>
</head>
<body>
    <form id="Form1" runat="server">
        <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> 
            <thead> 
            <tr> 
                <th>ID</th> 
                <th>Name</th> 
            </tr> 
            </thead> 
            <tbody> 
            <tr> 
                <td colspan="5" class="dataTables_empty">Loading data from server</td> 
            </tr> 
            </tbody> 
        </table>
    </form>
</body>
</html>

The example is oversimplified but I hope it will illustrate the basics on how to get stared.

Java HTML Builder (anti-template) library?

8 votes

I'm always looking for a modern Java library that makes creating valid (X)HTML snippets easy.

Yes you could use a templating language but there are times when you do not want to do this because Java has some advantages over insert your favorite templating language.

I have seen lots of in-house HTML builders in many projects but there is no Commons-HTML Builder that I can find.

Does anyone know of one?

It would be ideal if it took advantage of the Java 5/6/7 type system (generics) and support Fluent Style. Or something like fluent style ie JQuery style chaining, or a state machine used in mocking libraries like JMock (pedantically speaking a Monad).

A rough builder example might be:

new Html().title("stuff").body().in().div().in().h1("Hello World").hr();

Another example: http://codemonkeyism.com/the-best-markup-builder-i-could-build-in-java/

I ended up writing my own: Java Anti-template Language (JATL)

I ended up writing my own library called Java Anti-template Language (JATL)