Best javascript questions in August 2010

Looking for a question that combines the understanding of few web technologies

33 votes

I am teaching a web development course at a CS department, I wrote most of the final test by now, each question focus on a specific feature or a specific technology,

I wonder if you can think of/recommend a question that combine the knowledge of few technologies..

The course mostly covers: HTML, CSS, JS, HTTP, Servlets, JSP and JDBC. (as well as AJAX, ORM, basic security issues like SQL-Injection and XSS, HTML5, REST APIs)

EDIT: I will super appreciate questions with answers :-) thanks!

I'll give the bounty to the question with the highest rank, so please vote! I honestly like most of the questions here, thank you all :-)

Explain the relationship of the DOM to each of the following technologies: HTML, CSS, JavaScript.

The goal here is for the answer to make clear the student understands that HTML generates a DOM structure, CSS affects how that structure is rendered, and JavaScript affects how that structure is modified. If you understand how it all ties back into the DOM, all client-side coding becomes straightforward.

How can I get better at OOP?

25 votes

This might come as a strange question to many of you, and I don't actually know if it is correct to say OOP in this context, because OOP (object-oriented programming) is usually associated with programming languages like C++ and Java, and not lightweight programming languages, or scripting languages. My question, however, is in the category of JavaScript, which is also object oriented. I do know about objects, properties, methods, prototypes and constructors, I just can't seem to get into my mind when to use objects.

When I am writing my web-applications, I, for some reason, never use objects. This annoys me, because when I read about objects in a variety of books and online articles, objects make everything so much simpler and, just to put it out there, I HATE repeating myself, and this is why I wish I knew when to use objects.

I really want to become better at using objects and when to use objects.

Can you please mention a few situations objects would be good? It would be really nice to have written down something you know you can go back and look at when you get confused about when to use these darn objects :)

I would love simple answers explaining why and when objects are to prefer.
I would also like if you could tell me if I am to use objects when I am in some special situations generally suitable for objects i.e. every time you want to ___ then you use an object...


I really hope you understand my question and you will consider that I'm somewhat new to this site and new to JavaScript

Thanks!

You probably use objects without even realizing it.

If you're writing Javascript that interacts with the DOM, you're using objects.

If you're using any of the Javascript frameworks out there (jQuery, MooTools, etc.), you're using objects.

Using objects will be useful when you need to encapsulate some commonly used code so that it can be easily re-used (within a single application or across multiple applications like jQuery plugins...which are objects in and of themselves).

And to answer the question in the title of your post...the only way to really get better at OOP is to practice! Reading and studying the subject can only get you so far.

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.

node.js multi room chat example

24 votes

I'm looking for a websocket/node.js chat implementation which supports multiple rooms.

I'm also going to write an app which needs multiple rooms or servers, and I'm just looking for some code samples of how people do it.

Thanks.

I know there's a service http://pusherapp.com which provides this service, but I'm looking for an open source example.

I realised that you have not received a solution to your issue yet. Suggest looking at this question where i have provided the answer:

node-websocket-server: possible to have multiple, separate "broadcasts" for a single node.js process?

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.

Best way to check for "undefined" in javascript

21 votes

Possible Duplicates:
Detecting an undefined object property in JavaScript
How to check for undefined in javascript?

What is the most appropriate way to test if a variable is undefined in js? I've seen people use

if (window.myVariable) 

also

if (typeof(myVariable) != "undefined")

and

if (myVariable) //this throws an error if undefined, should this be in Try/Catch?

If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example.

// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"

But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.

"theFu" in window; // true
"theFoo" in window; // false

If you are interested in knowing whether the variable hasn't been declared or has the value undefined, then use the typeof operator.

if(typeof myVar != 'undefined')

The typeof operator is guaranteed to return a string. Direct comparisons against undefined are troublesome as undefined can be overwritten.

window.undefined = "omg";

"omg" == undefined // true

if(window.myVar) will also include all these falsy values, so it's not good:

false
0
""
NaN
null
undefined

Your third case - if (myVariable) should never throw an error.

Edit: The third case can only throw an error if it hasn't been declared at all, or you're using Object.defineProperty from ECMAScript 5th ed. where a property can have a backing function, and that backing function throws an error. For example.

// abc was never declared.
if(abc) {}

// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", { 
    get: function() { throw new Error("W00t?"); }, 
    set: undefined 
});
if(myVariable) {}

The if line will throw an error now. Try it in Chrome.

GWT "database" (client-side)

21 votes

I'm looking for something like a database for GWT objects (inside the browser). It must work without HTML5 or Gears (or any browser plugins). It doesn't have to be capable of everything a database can do, but the most important features would be

  • automated indexing, on multiple columns
  • some kind of API or language to perform (a limited subset of) queries

It could be a bit similar to Taffy DB, but it must have automated indexing, and it should provide a GWT API. I hope, it would be even smaller in download size than Taffy, if it re-uses code from the GWT library.

(Maybe I should add, that I don't need permanent storage. It's ok, if the data has to be reloaded/regenerated when the user hits reload.)

XBSDB seems to be good library for client-side db plus indexing solution.

Does a browser download JS files if the user has JS disabled?

18 votes

Does a browser download JS files if the user has JS disabled?

I'm wondering if the browser downloads the JS files and ignores them or ignores the download all together.

Do different browsers act differently in this case?

Edit:

I asked a follow up question to this question here.

Some testing (on Ubuntu 10.04) so far yields

  • Opera: doesn't download (disabled JS in preferences)
  • Firefox: doesn't download (disabled JS in preferences or with NoScript)
  • Google Chrome/Chromium: downloads (disabled JS via -disable-javascript parameter)
  • SRWare Iron (Chrome without the nonsense): doesn't download (disabled JS via "Options" - "Under The Hood" - "Content Settings" - "JavaScript" - "Content Settings" - "Do not allow any site to run JavaScript")
  • IE 8: doesn't download
  • IE 7: downloads

Edit: Made this a community wiki, so feel free to add your results.

"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.

Java or any other language: Which method/class invoked mine?

16 votes

I would like to write a code internal to my method that print which method/class has invoked it.

(My assumption is that I can't change anything but my method..)

How about other programming languages?

EDIT: Thanks guys, how about JavaScript? python? C++?

This is specific to Java.

You can use Thread.currentThread().getStackTrace(). This will return an array of StackTraceElements.

The 2nd element in the array will be the calling method.

Example:

public void methodThatPrintsCaller() {
    StackTraceElement elem = Thread.currentThread.getStackTrace()[2];
    System.out.println(elem);

    // rest of you code
}

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).

Javascript syntax: what comma means?

15 votes

If I use:

1.09 * 1; // returns "1.09"

But if I use:

1,09 * 1; // returns "9"

I know that 1,09 isn't a number. So, what comma does in the last piece of code?


EDIT 1

Another example:

if(0,9) alert("ok"); // alert

But

if(9,0) alert("ok"); // don't alert

EDIT 2

Yet Another example:

alert(1);alert(2);alert(3); // 3 alerts

And

alert(1),alert(2),alert(3); // 3 alerts too

EDIT 3

Crazy example:

alert("2",
    foo = function (param){
        alert(param)
    },
    foo('1')
)
foo('3'); // alerts 1, 2 and 3

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

Source: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Comma_Operator

For example, the expression 1,2,3,4,5 evaluates to 5. Obviously the comma operator is useful only for operations with side-effects.

Is there a tool for converting JavaScript to CoffeeScript?

14 votes

I'd love to use CoffeeScript, but converting all my JavaScript files doesn't seem like a task I should have to do by hand...

I brought this back guys, it's at http://mindynamics.github.com/js2cs

Sorry about this downtime, we were ungoing changes.

Thanks for the link!

jsilver MDX

Browser-based visual editor/designer?

14 votes

Is there an example of a browser-based and preferably open source visual javascript application designer (using contenteditable or canvas or whatever), perhaps with support for embedded controls and so forth (checkboxes, buttons, etc., or ui controls for various javascript frameworks like jquery.ui, dojo, yui,...), OR else support for vector graphics and shapes and so forth (canvas/svg vector graphics designer).

One example is ckeditor which has support for inserting html form controls (see the buttons on top right of the editor here): http://ckeditor.com/demo

And dojo's dojox has an example of a crude vector graphics editor ('drawing' I think the library is called).

There are some non-open source, commercial tools or similar tools out there like extjs designer, mockingbird (from cappucino).

And then I've found a few attempts at such things that didn't get too far, like qooxit, blok (using joose), and opus-js.

I have found one nice browser-based designer that is even open source, linb/jslinb, but it is completely undocumented and very complex and server-dependent (and many features are still not implemented yet).

Just wondering if there are any other options/examples out there, too. Thanks.

You're looking for something like the Forms designer from Visual Studio but for HTML? Sort of like Frontpage in Javascript?

I think you've enumerated the only two I know of in your question.

Get and Set a Single Cookie with Node.js HTTP Server

13 votes

I want to be able to set a single cookie, and read that single cookie with each request made to the nodejs server instance. Can it be done in a few lines of code, without the need to pull in a third party lib?

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

Just trying to take the above code directly from nodejs.org, and work a cookie into it.

There is no quick function access to getting/setting cookies, so I came up with the following hack:

var http = require('http');

http.createServer(function (request, response) {
  // To Get a Cookie
  var cookies = {};
  request.headers.cookie && request.headers.cookie.split(';').forEach(function( cookie ) {
    var parts = cookie.split('=');
    cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
  });

  // To Write a Cookie
  response.writeHead(200, {
    'Set-Cookie': 'mycookie=test',
    'Content-Type': 'text/plain'
  });
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

This will store all cookies into the cookies object, and you need to set cookies when you write the head.

What is the safest way of passing arguments from server-side PHP to client-size JavaScript

12 votes

In my application I rely heavily on JavaScript to enhance the user interface, but all of the data comes from a database and is processed by PHP. By default I use 'echo' statements to substitute the required values "just in time" like so:

var myVariable = <?php echo $myVariableInPHP ?>

This, however, does not strike me as very elegant and I am concerned about stability and maintainability of such code.

Do I have any alternatives here?

For server-side, I am using the Symfony 1.4 PHP framework.

Thanks,

My favorite way is :

<?php

$var = array(
  'prop1' => 'value1',
  'prop2' => 'value2',
  // ...
);

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

   alert( varNameSpace.prop1 ); // -> 'value1'
</script>

Using json_encode() ensures that the values passed to Javascript are escaped and well formatted. Using a common variable container also prevents from over using the global space (window).

What is the correct way to encode an inline javascript object, in order to protect it from XSS?

11 votes

It turns out the following which looks like valid javascript, is not:

<html> 
<body>
<script>
 json = {test: "</script><script>alert('hello');</script>"};
</script>
</body>
</html>

The same text, when returned JSON via an ajax api works just as expected. However when rendered in-line results in a basic XSS issues.

Given an arbitrary correct JSON string, what do I need to do server side to make it safe for in-line rendering?

EDIT Ideally I would like the fix to work with the following string as well:

json = {test: "<\/script><script>alert('hello');<\/script>"};

Meaning, I have no idea how my underlying library is encoding the / char, it may have chosen to encode it, or it may have not. (so its likely a regex fix is more robust)

To start with, this is not JSON at all, it's a Javascript object. JSON is a text format that is based on the Javascript syntax.

You can either make sure that the code doesn't contain the </ character combination:

var obj = { test: "<"+"/script><script>alert(\"hello\");<"+"/script>" };

Or if you are using XHTML you can make sure that the content in the script tag is interpreted as plain data:

<script type="text/javascript">
//<![CDATA[
var obj = { test: "</script><script>alert(\"hello\");</script>" };
//]]>
</script>

Why some professional web designers use absolute paths instead of relative paths (e.g for CSS, Javascript, images, etc.)?

10 votes

I used to think that everyone used relative paths (e.g. /styles/style.css). But I wonder why some popuar web designers (e.g. http://www.getfinch.com and http://31three.com/) use absolute paths (http://example.com/styles/style.css).

So basically I'm asking why some professional designers are using absolute paths instead of relative paths?

Both of those are using ExpressionEngine CMS, it's probably the way the CMS links the stylesheets.

But really it's just a matter of preference. Personally I go with root relative /css/main.css because this way if I'm developing locally + offline I don't have to worry about switching the WEB_ROOT constant to a local one ( less hassle + shorter ).

The only case I see for absolute is if the domain uses a CDN ( content delivery network ) and the domain is different from the origin domain.

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'.