Best javascript questions in April 2011

Is Javascript/jQuery DOM creation safe until it's added to the document?

28 votes

Please read this statement carefully: let's assume before ANY elements are added to the document all unsafe elements in $dom have been removed. But they were initially created. Ok let's continue....


If a piece of user text is processed and can possiblity be loaded like so:

var comment = 'I\'m a naughty person!!' +
              '<script src="http://blah.com/some_naughty_javascript.js">';
var $dom = $('<div>' + comment + '</div>');

Is this by itself dangerous in any way? My point being, can just the simple act of creating a DOM somehow inject anything, or is it just simply processed and the structure is created?

For example:

var $dom = $('<script>alert("hi");</script>');

Obviously the message hi does not pop up until it's added to the document. But:

  • Can any tag or anything created in this manner be dangerous?
  • Can any functions in javascript/jquery "watch" for elements being created in this manner and act on it BEFORE it's been stripped of bad elements and put on document?

Bounty Edit

So as outlined in the answers below, it seems this method isn't very safe, particularly for one reason:

  • var $dom = $('<img src="blah.jpg"/>') -- this will request for the image straight away, regardless of if the object was added to the document.

This creates a major problem for dealing with HTML ajax requests. For example if we wanted to get the values from the inputs of the form:

$.ajax({
  url: 'test.php',
  success: function(responseHTML) {
    var inputs = $(responseHTML).find('form input');
  }
});

This will involuntarily cause all images to be requested for by the browser.

Bounty is awarded to anyone:

  • Who can provide a nice, safe way of dealing with ajax requests without the above issue.
  • Ideally doesn't provide a regex answer... i.e. what if we wanted to do $(responseHTML).find('img') -- removing image tags with regex can't be an option, so an unobtrusive way would be needed to stop the src from loading, but still have the same attributes, structure, etc.

Is this by itself dangerous in any way? My point being, can just the simple act of creating a DOM somehow inject anything, or is it just simply processed and the structure is created?

Simply creating an element without appending it to the dom will not cause any script to run since it is purely an object at this point (HtmlScriptElement). When it is actually appended to the dom the script element will be evaluated and ran by the browser. With that being said I suppose it is possible that an extremely crafty person could exploit a bug that is present in some framework or browser you might be using to cause an undesired outcome.

Consider this example:

<p>
    <input type="button" value="Store 'The Script' In Variable" id="store"/>
    <input type="button" value="Append 'The Script' To Dom" id="append"/>
</p>
<br/>
<p>
    <input type="button" value="Does nothing"/>
</p>
<h1>The Script</h1>
<pre id="script">
    $(function(){
        function clickIt(){
            $(this).clone().click(clickIt).appendTo("body");
        }
        $("input[type='button']").val("Now Does Something").click(clickIt);
    });
</pre>

var theScript;

$("#store").click(function() {
    theScript = document.createElement('script');
    var scriptText = document.createTextNode($("#script").text());
    theScript.appendChild(scriptText);
});

$("#append").click(function() {
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(theScript);
});

When you click on store it will create the HtmlScriptElement and store it into a variable. You will notice that nothing is ran even though the object is created. As soon as you click append the script is appended to the dom and immediately evaluated and the buttons do something different.

Code Example on jsfiddle


Can any functions in javascript/jquery "watch" for elements being created in this manner and act on it BEFORE it's been stripped of bad elements and put on document?

jQuery sort of does that for you already as it does some internal script eval


From Karl Swedberg post on .append()

All of jQuery's insertion methods use a domManip function internally to clean/process elements before and after they are inserted into the DOM. One of the things the domManip function does is pull out any script elements about to be inserted and run them through an "evalScript routine" rather than inject them with the rest of the DOM fragment. It inserts the scripts separately, evaluates them, and then removes them from the DOM. ...

You could alter the behavior of jQuery to remove all <script/> and sanitize other elements with inline javascript onclick, mouseover, etc when calling append() however that will only affect jQuery as someone could easily use vanilla javascript to append the <script/> element.

Dom Mutation Events

Dom Level 2 does defined some Dom mutation events to capture elements that are added to the dom one would look towards the event, DOMNodeInserted. However it is fired after the element has already been added. note, per Raynos these are currently deprecated.

DOMNodeInserted Fired when a node has been added as a child of another node. This event is dispatched after the insertion has taken place. The target of this event is the node being inserted. Bubbles: Yes Cancelable: No Context Info: relatedNode holds the parent node

In the end it appears there is no totally stop a <script/> being appended to the dom via some other javascript. (at least not that I can find).

The best way I can suggest is to never ever trust user input as all user input is evil. When you do dom manipulation double check to make sure there are no forbidden tags, be it <script/> or even plain <p/> elements and sanitize all input before it is persisted.

Also as John points out you need to worry about any element that can attach a onclick event or any inline javascript event handler.

HTML5 Boilerplate vs. HTML5 Reset

27 votes

Hey everyone — HTML5 Boilerplate and HTML5 Reset are two HTML, CSS, and JavaScript templates with a lot of modern best practices built-in. Their goals are largely the same:

  • Fast, robust, modern Web development
  • HTML5 (duh!)
  • Cross-browser normalization (including support for IE6 and mobile browsers)
  • Progressive enhancement and graceful degradation
  • Performance optimizations
  • Not a framework, but the starting point for your next project

Obviously, they're very similar in function. In what ways are their implementations different (for example, perhaps IE-specific CSS fixes are achieved using different techniques)? Are they at all different in scope? It seems like HTML5 Boilerplate is a bit larger (build tools, server configuration, etc.), but it's hard to know where it goes beyond HTML5 Reset when it comes to the actual site that people will see.

In general, both projects set out to provide a solid starting point for developers working on web projects. They both get rid of a lot of the tedious, some-what error-prone boilerplate that many developers find themselves re-creating for each project. The details in how they go about it are slightly different, but for the most part, they achieve the same results.

HTML5Boilerplate has, as you noted, added in some build-script pieces to help developers follow best practices to speed up their pages in terms of server-side items, such as far-future expires headers, etc. where-as the HTML5Reset project is more focused on the semantics, content, and styling. For example, HTML5Reset has more example structure for the content of the page in HTML5 (to help show people how to use some of the new elements), whereas HTML5Boilerplate does not.

The response-time and page speed parts that HTML5Boilerplate includes get more and more important as more users find themselves on mobile platforms, and as Google increases the effect page response times have on page rank. There are lots of papers that show a small increase in the page response time has a measurable negative impact on how your site is used and perceived (especially in an eCommerce setting...often a 100ms slower page will get percentage less things sold).

On the CSS front, the majority of the reset style section for both projects is very much the same, with some minor differences in what the baseline is set to. The IE specific fixes, however, are largely the same, with HTML5Boilerplate asserting a bit more control than HTML5Reset over how IE styles some things like form elements (ie. check box / radio buttons and valid / invalid states)

Two major CSS areas that HTML5Boilerplate covers that HTML5Reset does not are common helper classes to assist with making sites more accessible, such as .hidden and .visuallyhidden, as well as some substantial adjustments to the print styles that serve to both make printing more similar across browsers, as well as some cost-savings and accessibility things like making background images transparent (to not waste toner), and adding the actual URL to links and the title to abbreviations.

I would highly suggest reading through both projects' info and how they do things in a side-by-side comparison because the similarities, and also the differences (and the reasoning behind them) is quite informative and has helped me to better decide what parts of each I wanted to use.

Ultimately, just like any "library" sort of project, you as the developer need to understand what you are doing and probably should tweak your baseline to meet the particular needs of the project.

Is JavaScript's double equals (==) symmetric?

24 votes

There are many cases in which JavaScript's type-coercing equality operator is not transitive. (See, for instance, JavaScript equality transitivity is weird....) But are there any cases in which it isn't symmetric—that is, where a == b is true but b == a is false?

Edit: In my original question, I mistakenly said "reflexive" rather than "symmetric." Thanks to all who corrected me on this point.

You have the wrong term.

Reflexive means a != a.
The Javascript == relation is almost always reflexive, except that NaN != NaN.


The word you're looking is symmetric.
In Javascript, == is always symmetric.

The spec says:

NOTE 2 The equality operators maintain the following invariants:

  • A != B is equivalent to !(A == B).
  • A == B is equivalent to B == A, except in the order of evaluation of A and B.

Why are there two kinds of JavaScript strings?

22 votes

This one just stabbed me hard. I don't know if it's the case with all browsers (I don't have any other competent browser to test with), but at least Firefox has two kind of string objects.

Open up the Firebugs console and try the following:

>>> "a"
"a"
>>> new String("a")
String { 0="a"}

As you can visually observe, Firefox treats new String("a") and "a" differently. Otherwise however, both kinds of strings seem to behave the same. There is, for instance, evidence that both use the same prototype object:

>>> String.prototype.log = function() { console.log("Logged string: " + this); }
function()
>>> "hello world".log()
Logged string: hello world
>>> new String("hello world").log()
Logged string: hello world

So apparently, both are the same. That is, until you ask for the type.

>>> typeof("a")
"string"
>>> typeof(new String("a"))
"object"

We can also notice that when this is a string, it's always the object form:

>>> var identity = function() { return this }
>>> identity.call("a")
String { 0="a"}
>>> identity.call(new String("a"))
String { 0="a"}

Going a bit further, we can see that the non-object string representation doesn't support any additional properties, but the object string does:

>>> var a = "a"
>>> var b = new String("b")
>>> a.bar = 4
4
>>> b.bar = 4
4
>>> a.bar
undefined
>>> b.bar
4

Also, fun fact! You can turn a string object into a non-object string by using the toString() function:

>>> new String("foo").toString()
"foo"

Never thought it could be useful to call String.toString()! Anyways.

So all these experiments beg the question: why are there two kinds of strings in JavaScript?


Comments show this is also the case for every primitive JavaScript type (numbers and bools included).

There are two types of strings in Javascript -- literal strings and String objects. They do behave a little differently. The main difference between the two is that you can add additional methods and properties to a String object. For instance:

var strObj = new String("object mode");
strObj.string_mode = "object"
strObj.get_string_mode = function() { return this.string_mode; }

// this converts it from an Object to a primitive string:
str = strObj.toString();

A string literal is just temporarily cast to a String object to perform any of the core methods.

The same kinds of concepts apply to other data types, too. Here's more on primitive data types and objects.

EDIT

As noted in the comments, string literals are not primitive strings, rather a "literal constant whose type is a built-in primitive [string] value", citing this source.

javascript function leading bang ! syntax

21 votes

I've been seeing this syntax on a few libraries now and I'm wondering what the benefit is. (note i'm well aware of closures and what the code is doing, I'm only concerned about the syntactical differences)

!function(){
  // do stuff
}();

As an alternative to the more common

(function(){
  // do stuff
})();

for self invoking anonymous functions.

I'm wondering a few things. First off, what is allowing the top example to actually work? Why is the bang necessary in order to make this statement syntactically correct? I'm told also that + works, and I'm sure some others, in place of !

Second, what is the benefit? All I can tell is that it saves a single character, but I can't imagine that's such a huge benefit to attract numerous adopters. Is there some other benefit I"m missing?

The only other difference I can see would be the return value of the self invoking function, but in both of these examples, we don't really care about the return value of the function since it's used only to create a closure. So can someone tell me why one might use the first syntax?

Ideally you should be able to do all this simply as:

function(){
  // do stuff
}(); 

That means declare anonymous function and execute it. But that will not work due to specifics of JS grammar.

So shortest form of achieving this is to use some expression e.g. UnaryExpression (and so CallExpression):

!function(){
  // do stuff
}(); 

Or for fun:

-function(){
  // do stuff
}(); 

Or:

+function(){
  // do stuff
}(); 

Or even:

~function(){
  // do stuff
  return 0;
}( );

return false the same as return?

15 votes

Is

return false 

the same as:

return

No.

var i = (function() { return; })();

i === undefined which means that i == false && i == '' && i == null && i == 0 && !i

var j = (function() { return false; })();

j === false which means that j == false && j == '' && j == null && j == 0 && !j

Weak operators in JS make it seem like the might return the same thing, but they return objects of different types.

Shortest function for reading a cookie in JavaScript

14 votes

What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?

Very often, while building stand-alone scripts (where I can't have any outside dependencies), I find myself adding a function for reading cookies, and usually fall-back on the QuirksMode.org readCookie() method (280 bytes, 216 minified.)

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

It does the job, but its ugly, and adds quite a bit of bloat each time.

The method that jQuery.cookie uses something like this (modified, 165 bytes, 125 minified):

function read_cookie(key)
{
    var result;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}

Note this is not a 'Code Golf' competition: I'm legitimately interested in reducing the size of my readCookie function, and in ensuring the solution I have is valid.

This will only ever hit document.cookie ONE time. Every subsequent request will be instant.

(function(){
    var cookies;

    function readCookie(name,c,C,i){
        if(cookies){ return cookies[name]; }

        c = document.cookie.split('; ');
        cookies = {};

        for(i=c.length-1; i>=0; i--){
           C = c[i].split('=');
           cookies[C[0]] = C[1];
        }

        return cookies[name];
    }

    window.readCookie = readCookie; // or expose it however you want
})();

I'm afraid there really isn't a faster way than this general logic unless you're free to use .forEach which is browser dependent (even then you're not saving that much)

Your own example slightly compressed to 120 bytes:

function read_cookie(k,r){return(r=RegExp('(^|; )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}

You can get it to 110 bytes if you make it a 1-letter function name, 90 bytes if you drop the encodeURIComponent.

I've gotten it down to 73 bytes, but to be fair it's 82 bytes when named readCookie and 102 bytes when then adding encodeURIComponent:

function C(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}

What is your experience with Android webapps (limitations, tips, best practices)?

14 votes

Update:

As François mentioned, there are alternatives such as Phone Gap for a more cross-platform approach. It's a very good suggestion indeed. I'm open to any suggestions and I would really appreciate if I can learn from your experience.
Sidenote: A web-only app is not high on my list of options, since I do want it to be on the android market.


I'm about to start porting a facebook app to android and I'm debating whether I should write it as a native app or as a wrapper for a glorified WebView.

How is your experience? What limitations did you face when writing a webapp? Do you have any advice you may want to share? Maybe you think that a native app is the way to go instead?

To set up a famework for the discussion, the app I want to port right now is a simple fb app, in which the server is hosted in Google App Engine (written in Java, if that matters), and all the client code is html, css and javascript (with a good amount of jQuery).

The app is basically a two player, turn-based game, with a bunch of static images that respond to user clicks, and a very simple chat box (independent of fb chat). It can handle several concurrent games for each user (but to different opponents, not the same).

Do you think is a good fit for an Android webapp?

Thank you in advance.

PS1: By all means, I will appreciate any insight, so please do not limit yourself to this specific example app should you want to be broader in your answer.

PS2: Yes, I read the "Best Practices for Web Apps" page from developer.android.com, and I followed the links there, but it does not say much about speed or reliability of the WebView component, specially in terms of user interaction. The question comes after reading the following paragraphs in the WebView description page, which kind of limits the typical scenarios quite a bit:

A common scenario in which using WebView is helpful is when you want to provide information in your application that you might need to update, such as an end-user agreement or a user guide. Within your Android application, you can create an Activity that contains a WebView, then use that to display your document that's hosted online.

Another scenario in which WebView can help is if your application provides data to the user that always requires an Internet connection to retrieve data, such as email. In this case, you might find that it's easier to build a WebView in your Android application that shows a web page with all the user data, rather than performing a network request, then parsing the data and rendering it in an Android layout. Instead, you can design a web page that's tailored for Android devices and then implement a WebView in your Android application that loads the web page.

Hi,

I have implemented two projects that use webview, one is with jqtouch and other with jquery-mobile frameworks.

You are starting like a breeze and go on, but at last when you look at the application it is very far from native user experience. Android browser is much more slower than iphone browser. Hope it will be resolved later, as a result you will have slower response times when you are dealing with css3 heavy applications. While developing in emulator, webview will make you mad as it is sooo slow.

If you want to implement native like elements or fixed tabbar you are working a lot and at last not getting a good solution when you compare your application with native applications, it just sucks.

At last I have decided to learn native development and being a first class citizen. Of course this will take much more time but the result will satisfy me.

I think native development is not the future, sometime later we will write html-css-js applications again and they will work like native code, but it is not likely to be in 2-3 years according to my opinion.

I can suggest you that, try building web apps, if performance does not satisfies you like me, then switch to native development.

Is there any single tool that runs JSLint, W3C validator (both CSS3 and HTML5) on files in a given directory?

14 votes

I want a single program that recursively finds all *.js, *.html and *.css files in a given directory and JSLints, and W3C validates them respectively and prints out all errors found. Also it separately JSLints and CSS validates anything found inside script and style tags embedded in the html files. I also want this to validate other less common web contents too if possible using the W3C tools. The tools should also have option for passing in common JavaScript frameworks for JSLint (e.g. it should work fine with latest JQuery). Where I can buy such a tool?

CSE Validator - http://www.htmlvalidator.com/

Test-driven development of JavaScript web frontends

13 votes

This might sound a little dumb, but I'm actually a bit confused how to approach JavaScript testing for web frontends. As far as I'm concerned, the typical 3-tier architecture looks like this:

  1. Database tier
  2. Application tier
  3. Client tier

1 is of no concern in this question. 2 contains all the program logic ("business logic") 3 the frontend.

I do test-driven development for most projects, but only for the application logic, not the frontend. That is because testing the UI is difficult and unusual in TDD, and normally not done. Instead, all application logic is separated from UI, so that it is simple to test that logic.

The three tier architecture supports this: I can design my backend as a REST API which is called by my frontend. How does JS testing fit in? For the typical three-tier-architecture, JS (i.e. JS on the client) testing doesn't make much sense, does it?

Update: I've changed the question's wording from "Testing JavaScript in web frontends" to "Test-driven development of JavaScript web frontends" to clarify my question.

Remember what the point of unit-testing is: to ensure a particular module of code reacts to some stimuli in an expected manner. In JS, a significant portion of your code, (unless you have some lifecycle framework like Sencha or YUI) will either be directly manipulating the DOM or making remote calls. To test these things, you simply apply traditional unit-testing techniques of dependency injection and mocking/stubbing. That means you must write each function, or class, that you want to unit-test to accept mocks of the dependent structures.

jQuery supports this by allowing you to pass an XML document into all traversal functions. Whereas you might normally write

$(function() { $('.bright').css('color','yellow'); }

you'll instead want to write

function processBright(scope) {
    // jQuery will do the following line automatically, but for sake of clarity:
    scope = scope || window.document;

    $('.bright',scope).css('color','yellow');
}

$(processBright);

Notice we not only pull the logic out of the anonymous function and give it a name, we also make that function accept a scope parameter. When that value is null, the jQuery calls will still function as normal. However, we now have a vector for injecting a mock document that we can inspect after the function is invoked. The unit-test could look like

function shouldSetColorYellowIfClassBright() {
    // arrange
    var testDoc = 
        $('<html><body><span id="a" class="bright">test</span></body></html>');

    // act
    processBright(testDoc);

    // assert
    if (testDoc.find('#a').css('color') != 'bright')
        throw TestFailed("Color property was not changed correctly.");
}

TestFailed could look like this:

function TestFailed(message) {
    this.message = message;
    this.name = "TestFailed";
}

The situation is similar with remote calls, though rather than actually injecting some facility, you could get away with a masking stub. Say you have this function:

function makeRemoteCall(data, callback) {
    if (data.property == 'ok') 
        $.getJSON({url:'/someResource.json',callback:callback});
}

You would test it as such:

// test suite setup
var getJSON = $.getJSON;
var stubCalls = [];
$.getJSON = function(args) {
    stubCalls[stubCalls.length] = args.url;
}

// unit test 1
function shouldMakeRemoteCallWithOkProperty() {
    // arrange
    var arg = { property: 'ok' };

    // act
    makeRemoteCall(arg);

    // assert
    if (stubCalls.length != 1 || stubCalls[0] != '/someResource.json')
        throw TestFailed("someResource.json was not requested once and only once.");
}

// unit test 2
function shouldNotMakeRemoteCallWithoutOkProperty() {
    // arrange
    var arg = { property: 'foobar' };

    // act
    makeRemoteCall(arg);

    // assert
    if (stubCalls.length != 0)
        throw TestFailed(stubCalls[0] + " was called unexpectedly.");
}

// test suite teardown
$.getJSON = getJSON;

(You can wrap that whole thing in the module pattern to not litter the global namespace.)

To apply all of this in a test-driven manner, you would simply write these tests first. This is a straightforward, no frills, and most importantly, effective way of unit-testing JS.

Frameworks like qUnit can be used to drive your unit-tests, but that is only a small part of the problem. Your code must be written in a test-friendly way. Also, frameworks like Selenium, HtmlUnit, jsTestDriver or Watir/N are for integration testing, not for unit-testing per se. Lastly, by no means must your code be object-oriented. The principles of unit-testing are easily confused with the practical application of unit-testing in object-oriented systems. They are separate but compatible ideas.

Testing Styles

I should note that two different testing styles are demonstrated here. The first assumes complete ignorance of the implementation of processBright. It could be using jQuery to add the color style, or it could be doing native DOM manipulation. I'm merely testing that the external behavior of the function is as expected. In the second, I assume knowledge of an internal dependency of the function (namely $.getJSON), and those tests cover the correct interaction with that dependency.

The approach you take depends on your testing philosophy and overall priorities and cost-benefit profile of your situation. The first test is relatively pure. The second test is simple but relatively fragile; if I change the implementation of makeRemoteCall, the test will break. Preferably, the assumption that makeRemoteCall uses $.getJSON is at least justified by the documentation of makeRemoteCall. There are a couple more disciplined approaches, but one cost-effective approach is to wrap dependencies in wrapper functions. The codebase would depend only on these wrappers, whose implementations can be easily replaced with test stubs at test-time.

Normalizing mousewheel speed across browsers

13 votes

For this question I composed this answer, including this sample code.

In that code I use the mouse wheel to zoom in/out of an HTML5 Canvas. I found some code that normalizes speed differences between Chrome and Firefox. However, the zoom handling in Safari is much, much faster than in either of those.

Here's the code I currently have:

var handleScroll = function(e){
  var delta = e.wheelDelta ? e.wheelDelta/40 : e.detail ? -e.detail/3 : 0;
  if (delta) ...
  return e.preventDefault() && false;
};
canvas.addEventListener('DOMMouseScroll',handleScroll,false);
canvas.addEventListener('mousewheel',handleScroll,false);

What code can I use to get the same 'delta' value for the same amount of mouse wheel rolling across Chrome v10/11, Firefox v4, Safari v5, Opera v11 and IE9?

This question is related, but has no good answer.

Edit: Further investigation shows that one scroll event 'up' is:

                  | evt.wheelDelta | evt.detail
------------------+----------------+------------
  Safari v5/OS X  |       120      |      0
  Safari v5/Win7  |       120      |      0
Chrome v11b/OS X  |         3 (!)  |      0
Chrome v11b/Win7  |       120      |      0
        IE9/Win7  |       120      |  undefined
  Opera v11/OS X  |        40      |     -1
  Opera v11/Win7  |       120      |     -3
 Firefox v4/OS X  |    undefined   |     -1
 Firefox v4/Win7  |    undefined   |     -3

So the question is:

What is the best way to differentiate this behavior (ideally without any user agent or OS sniffing)?

Here is my first attempt at a script to normalize the values. It has two flaws on OS X: Firefox on OS X will produce values 1/3 what they should be, and Chrome on OS X will produce values 1/40 what they should be.

// Returns +1 for a single wheel roll 'up', -1 for a single roll 'down'
var wheelDistance = function(evt){
  if (!evt) evt = event;
  var w=evt.wheelDelta, d=evt.detail;
  if (d){
    if (w) return w/d/40*d>0?1:-1; // Opera
    else return -d/3;              // Firefox;         TODO: do not /3 for OS X
  } else return w/120;             // IE/Safari/Chrome TODO: /3 for Chrome OS X
};

You can test out this code on your own browser here: http://phrogz.net/JS/wheeldelta.html

Suggestions for detecting and improving the behavior on Firefox and Chrome on OS X are welcome.

Edit: One suggestion from @Tom is to simply count each event call as a single move, using the sign of the distance to adjust it. This will not give great results under smooth/accelerated scrolling on OS X, nor handle perfectly cases when the mouse wheel is moved very fast (e.g. wheelDelta is 240), but these happen infrequently. Here is simpler code that does just that:

var wheelDirection = function(evt){
  if (!evt) evt = event;
  return (evt.detail<0 || evt.wheelDelta>0) ? 1 : -1;
};

IE9: Why setting "-ms-transform" works from css, but not with jquery.css()

13 votes

This works

div{
    -ms-transform: rotate(30deg);
}

And following does not

$("div").css("-ms-transform","rotate(30deg)");

Any ideas why, and how to fix it?
Same thing works good on all other browsers, but not on IE. Ofcourse, only IE9 supports it. Older versions dont.

Not sure why As KooiInc says, dashes in style property names are invalid in DOM scripting.

You can fix it by using object notation and passing in the name in camel case instead of hyphenated, like this:

$('div').css({ msTransform: 'rotate(30deg)' });

jsFiddle preview

Where does JavaScript sit in the MVC pattern of a web application?

11 votes

I'm still confused about where JavaScript code sits in the MVC pattern when building a web application. I thought it worked like this.

  • The Model is the database and the classes required to get the data in/out.
  • The Controller would be the Classes where I write my logic that is, Java servlets, which accept an Ajax request and then make a call to the database;
  • The View is the JSP page which is returned to the Ajax request via the servlet (my Controller)

Because JavaScript code is compiled in the browser I think of it as part of the View, but it's handling user inputs, making server requests based on those events and then returning the data to page, so would that also make in part of the Controller?

Also, what does it mean when they refer to the Domain Model in MVC?

JavaScript is going to be primarily a UI related concern; your view is making an ajax request to the controller. The controller isnt making an ajax request; nor is the model. For all intents and purposes, an ajax request isnt anything different than a normal request; it's just that the browser isnt hanging until your response is returned.

JavaScript also executes in the context of your client, outside the purview of your server, so it should go into the view.

Help me convince a teacher that he needs to stop teaching IE filters!

11 votes

The Issue

Just to give you some background, I'm currently enrolled as a student at the University of Mary Hardin-Baylor. Currently the web design classes there are somewhat... sub-par. My DHTML teacher worked on websites in the Netscape/IE clash and most of the stuff he teaches is deprecated, non-semantic HTML, or inline code. He is still a huge supporter of IE and is still avid about students learning IE filters. From what I've seen he seems to see no need to support multiple browsers. I'd really like to see the web design section of the school grow and as long as the teachers are still teaching deprecated code, it probably won't. I'm planning on sending him an e-mail trying to convince him to drop the IE filters section of the course next semester and replace it with something that students will actually be able to use cross-browser.

The Request

I need help building my argument.

  • I need to build a list of reasons on why filters are deprecated and shouldn't be used(I believe they aren't even supported in IE9 anymore).
  • It might also be advantageous to give reasons why cross-browser support should be achieved.
  • I need some reputable sources that I can quote. This excludes sites like wikipedia.

Also, on a side note, one of the reasons I'm asking this here is because I don't have any type of real world coding experience. If I had support from someone else who worked in the same era of the web, it could do wonders for the legitimacy of my argument. I don't want this to sound like I'm just bashing his methods, or even worse... just trying to get out of work.

Thank you in advance for any help you post! I know this is a huge request. I appreciate any time your willing to give.

Edit

I just wanted to point out that I agree with some of the comments made. The filters section of the course is a very minor problem. There is a numerous amount of other issues that would be far more important if the students were going into a web design career. Unfortunately most of the students are forced into this class specifically for degree requirements of the CGD Major. There currently is no major dedicated to web design and there are probably only 4 people on campus that actually are pursuing web design as a career. The average Joe of this class will probably never produce more than a personal website. This being said, version compatibility and other issues solved by filters will probably never be used.

The main issue isn't that the teacher is teaching IE filters, though, it's that he's teaching a three week section on filters. Through the entire semester, the class has only been able to go over very simple Javascript such as variables, functions, arrays, loops, and attaching events via event attributes. We haven't even touched the DOM yet and the stuff we have gone over we only touched on very lightly. I would just like to see the last section of the class dedicated to the more universally useful information such as the DOM, Objects, Object methods, and Regular Expressions.

Despite all of this though will be making a large section of the document over browser compatibility and I appreciate the information y'all have supplied for that. I wish I could tell him everything that he's doing wrong, but that would be way more than one e-mail. I would like to take it one step at a time though and at least point him in the right direction.

Sorry for the long post! Thanks

Cross-browser support:

  • If it's a project for a client: What do you tell your client if the site you created does not work on non-ie browsers? Actually usually clients require cross-browser compatibility.
  • Only supporting IE means losing customers which means losing money
  • Why use proprietary filters if cross-browser alternatives exist? IE9 supports CSS3, opacity etc
  • Modern developer tools facilitate and support modern technologies - and all developers want to use shiny new tools (they're more fun :-))
  • Forward compatibility: You may create an ie-only site with table-layouts and proprietary filters, but you will need to start from scratch once you'll realize what you've done, whereas building a site based on today's standards will be maintainable longer before a complete remake is due.
  • Maintenance: A web site needs to be maintained, probably by different people - choosing current and well-known technologies will make this easier.
  • It's not that hard (once you exclude IE6 - see compatibility table linked below)

Some sources:

  • Browser compatibility by PKK, for example CSS: http://www.quirksmode.org/css/contents.html Excellent resource for implementing cross-browser compatible web sites. PPK is one of many professionals promoting cross-browser compatible web sites, you won't find the contrary (professionals promoting IE only sites).
  • Even Microsoft promotes moving on from IE6 towards modern browsers and technologies, and is proud of ie9's CSS3 support: http://www.theie6countdown.com/default.aspx

display:none; displays 'none' in browser.

10 votes

This jsFiddle example works in Google Chrome, but in Internet Explorer then when the close icon is clicked the browser removes the pop-up element but results in the text 'none' being displayed in the browser window. Please explain how I can resolve this issue.

Use onclick for the event handler instead of href http://jsfiddle.net/AE2X3/4/

<div id="popup">
        <a href="#" onclick="document.getElementById('popup').style.display='none';return false;" id="close_popup"></a>
        <p>This is a pop-up.</p>
</div>

Javascript console.log() on HTC Android devices and adb logcat

9 votes

I am developing the application in HTML which is calling the console.log() from Javascript to provide me logs during the development about what happens in the web page code.

Unfortunately when I use the adb logcat command to check logs I can see output from all other applications, but not the output from my JavaScript code. I can see even the log from web browser that the page is loaded, but not console.log() output from my JavaScript code executed in the web browser.

According to information on this page (http://developer.android.com/guide/webapps/debugging.html) it should work.

I am testing on HTC WildFire and HTC Desire HD.

I have been using three different HTC phones, almost exclusively, and have never had this issue. Here are a few things to check:

  1. Make sure USB debugging is enabled.
  2. Make sure your Webview has a WebChromeClient set. The browser used in Webview does not implement console.log().
  3. It should be easy to see the output of adb logcat, but to make it easier, filter the output.

Turn on USB debugging:

  1. Disconnect your device from your computer.
  2. Go to Settings -> Applications -> Development -> Select "Enable USB Debugging"
  3. Plugin to computer. (Make sure you have the correct drivers installed to use ADB - more info here: http://developer.android.com/guide/developing/device.html)

Set a WebChromeClient that overrides onConsoleMessage():

//Set the output prefix so you can filter adb logcat results later
public static final String TAG = "Your-Application-Name";

myWebView = (WebView) findViewById(R.id.webview);

//Not going to have much luck running JS without this:
myWebView.getSettings().setJavaScriptEnabled(true);

//Override onConsoleMessage() to output to the Log.
myWebView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onConsoleMessage(ConsoleMessage cm) {
        Log.d(TAG, cm.message() + " -- From line "
        + cm.lineNumber() + " of "
        + cm.sourceId() );
        return true;
    }
});

More info on onConsoleMessage() here: http://developer.android.com/reference/android/webkit/WebChromeClient.html#onConsoleMessage(java.lang.String, int, java.lang.String)

More info on debugging in general here: http://developer.android.com/guide/webapps/debugging.html

Filter the output of adb logcat:

adb logcat tag-name:log-level *:S

tag-name matches the string specified in Log.x log-level matches the log level you indicated when calling Log.x <---

Example relating to code above:

adb logcat Your-Application-Name:D *:S

This will show all d level logs for the matching tag, Your-Application-Name, and silence everything else.

More info on adb filtering here: http://developer.android.com/guide/developing/tools/adb.html#logcat

Hope it helps! I know it was a bit of summarizing of the other answers, but, the fact is, it takes all of the steps to make it work. :)

Combine jQuery and Zen-Coding php ports to emulate client side programming style on server side scripts

9 votes

When I write client side code, I use HTML/CSS/JavaScript and lately jQuery to both speed up coding, and use improved methods to achieve the same goal.

In my text editor I use zen-coding to speed up the writing of code, and also to avoid errors. I was looking at zen-coding as a jQuery plugin for a while, but it has a fatal flaw, that you want the HTML to be written and sent to the client plain before any javascript kicks in.

Although we can use JavaScript servers (env.js or node.js) and therefore do a lot of development server side using JavaScript and jQuery, I am not comfortable moving over yet as it is an emerging technology, and has many differences and drawbacks (and also some major advantages).

I want to continue using PHP server side, but develop in the way I am most comfortable with, and familiar with which is client side JavaScript.

Therefore - I have been looking into QueryPath which is a PHP port of jQuery that aims to take the best and most relevant parts of jQuery and re-work it to suit the server environment.

That is all great, and I have now been looking at two PHP classes capable of parsing zen-coding which when combined acts as a great templating engine and also avoids errors in my code.

The problem I am having is that neither zen-coding parsers support anywhere near a full set of zen-coding features.

So finally my questions (sorry for the rather lengthy intro)

  1. Is there a better server side zen-coding parser I can use in my PHP code?
  2. Is there a good (very concise and full featured) alternative templating system to using zen-coding? (which I know is not originally designed for this task)
  3. Is there a better approach I should take to achieve my ultimate goal of narrowing the divide between the way I code client side and server side?
  4. Is there a PHP library that implements a load of utility functions that by using will enhance the security/performance of my code without me learning all the internal workings? (like jQuery does for javascript)

NB: I am looking more for functional equivalence than syntactic similarity - although both are a plus for me.

Here is some commented test code that should illuminate what I am trying to achieve:

<?php

    // first php based zen-coding parser
    // http://code.google.com/p/zen-php
    require_once 'ZenPHP/ZenPHP.php';
    // my own wrapper function
    function zp($abbr){ return ZenPHP::expand($abbr); }

    // second php based zen-coding parser
    // https://github.com/philipwalton/PW_Zen_Coder
    require_once 'PW_Zen_Coder/PW_Zen_Coder.php';
    $zc = new PW_Zen_Coder;
    // my own wrapper function
    function pwzc($abbr){ global $zc; return $zc->expand($abbr); }

    // php port of jQuery with a new server-side flavor
    // http://querypath.org/
    require_once 'QueryPath/QueryPath.php';

    // initialize query path with simple html document structure
    qp(zp('html>head+body'))

        // add a heading and paragraph to the body
        ->find('body')
        ->html(zp('h1{Zen Coding and jQuery - Server Side}+p{This has all been implemented as a php port of JavaScript libraries}'))

        // add a comments link to the paragraph
        ->find('p')
        ->append(pwzc('span.comments>a[href=mailto:this@comment.com]{send a comment}'))

        // decide to use some jquery - so add it to the head
        ->find(':root head')
        ->append(zp('script[type=text/javascript][src=/jquery.js]'))

        // add an alert script to announce use of jQuery
        ->find(':root body')
        ->append(zp('script[type=text/javascript]{$(function(){ alert("just decided to use some jQuery") })}'))

        // send it to the browser!
        ->writeHTML();

    /* This will output the following html

    <html>
    <head>
    <script type="text/javascript" src="/jquery.js"></script>
    </head>
    <body>
    <h1>
        Zen Coding and jQuery - Server Side
    </h1>
    <p>
        This has all been implemented as a php port of JavaScript libraries
    <span class="comments">
        <a href="mailto:this@comment.com">

            send a comment
        </a>
    </span>
    </p>
    <script type="text/javascript">
        $(function(){ alert("just decided to use some jQuery") })
    </script>
    </body>
    </html>

    */
?>

Any help is much appreciated

Hi Billy,

first of all i want to say i have up-voted your answer because it is well explained and have some nice point to consider; then i want let you think about theese other point:

GOTCHAS

  1. IMHO you are overcomplicating the whole thing ;)

  2. between the entire PHP code needed to generate the HTML and the outputted HTML itself there is very very low difference in term of lenght of writed-code.

  3. the code is completely unredeable for everyone who don't know the 3 libs or whatever it is.

  4. the speed of site-load will decrease enourmously compared to the semplicity of the vanilla HTML.

  5. what the real difference between:


h1{Zen Coding and jQuery - Server Side}+p{This has all been implemented as a php port of JavaScript libraries}

and

<h1>Zen Coding and jQuery - Server Side</h1><p>This has all been implemented as a php port of JavaScript libraries</p>

6.. as you know both zen-coding and queryPath are not intended to be used the way you are doing, at least not in a production scenario.

7.. The fact that jQuery have a good documentation and it's usefull to use doesn't mean that can be used successfully from anyone. ( the mere copy/past is not considered a coding skill IMO )

SOLUTION

it is probably the best solution for you looking at some kind of PHP Templating Engine like smarty, this will suit your needs in various way:

  1. security/performance
  2. narrowing the divide between the way I code client side and server side

an example would be: ( to be considered a very primitive example, smarty have more powerfull functionalities )

<!-- index.tpl -->
<html>
  <head> {$scriptLink} 
  </head>
  <body> <h1> {$h1Text} </h1>
    <p> {$pText} 
      <span class="comments">
        <a href="{$aLink}"> {$aText} </a>
      </span>
    </p> {$scriptFunc} 
  </body>
</html>

    // index.php
    require('Smarty.class.php');
    $smarty = new Smarty;
    $smarty->assign("scriptLink", "<script type=\"text/javascript\" src=\"/jquery.js\"></script>");
    $smarty->assign("scriptFunc", "<script type=\"text/javascript\">$(function(){ alert(\"hello world\") });</script>");
    $smarty->assign("h1Text", "Zen Coding and jQuery - Server Side");
    $smarty->assign("pText", "This has all been implemented as a php port of JavaScript libraries");
    $smarty->assign("aText", "send a comment");
    $smarty->assign("aLink", "mailto:this@comment.com|mailCheck");
    $smarty->display('index.tpl');

NOTE: the use of mailCheck, yes you should also consider eventuality some kind of variable check. smarty can do it....

hope this help. ;)

What is the purpose/benefit of using ignored parameters in a JavaScript function?

8 votes

Just so there is no misunderstanding, this question is not about allowing for optional parameters in a JS function.

My question is motiviated by the jQuery parseXML function, which is defined in jQuery.js as follows:

// Cross-browser xml parsing
// (xml & tmp used internally)
parseXML: function( data, xml, tmp ) { 
   ... 
} 

Within the body of the function, the parameters xml and and tmp are both assigned before they are used. That means they are being used as local variables, so the function could have been defined like this:

parseXML: function(data) { 
   var xml, tmp;
   ... 
}

What is the benefit of doing it the first way, other than saving a few characters in the minified version of jQuery.js?

If we define two functions...

function a ( foo ) { }
function b ( foo, bar, baz ) {}

...they'll report different lengths...

console.log( [a.length, b.length] ); // logs [1, 3]

It's very rare to see this little known feature of javascript used.

But apart from shaving a couple of bytes off the minified file-size, this is the only other reason that I can think of.

Are there any good node.js tutorials for absolute beginners?

8 votes

Are there any good and clear node.js tutorials for absolute beginners from A to Z?

I have moderate Javascript and jQuery skills.

Thank you very much.

DailyJS's nodepad tutorials.

It explains the fundamentals of creating a web app with node.js, by creating a notepad app with you, right from framework selection and installation, to databases, connectivity, templates and more.

It even includes full source code on github, so you can actually follow along.

The series is still running at the moment (at part 22, and updated weekly), so there's plenty of material to follow.

Does using $this instead of $(this) provide a performance enhancement?

8 votes

Hello,

Assume I have the following example:

Example One

$('.my_Selector_Selected_More_Than_One_Element').each(function() {
    $(this).stuff();
    $(this).moreStuff();
    $(this).otherStuff();
    $(this).herStuff();
    $(this).myStuff();
    $(this).theirStuff();
    $(this).children().each(function(){
        howMuchStuff();
    });
    $(this).tooMuchStuff();
    // Plus just some regular stuff
    $(this).css('display','none');
    $(this).css('font-weight','bold');
    $(this).has('.hisBabiesStuff').css('color','light blue');
    $(this).has('.herBabiesStuff').css('color','pink');
}

Now, it could be:

Example Two

$('.my_Selector_Selected_More_Than_One_Element').each(function() {
    $this = $(this);
    $this.stuff();
    $this.moreStuff();
    $this.otherStuff();
    $this.herStuff();
    $this.myStuff();
    $this.theirStuff();
    $this.children().each(function(){
        howMuchStuff();
    });
    $this.tooMuchStuff();
    // Plus just some regular stuff
    $this.css('display','none');
    $this.css('font-weight','bold');
    $this.has('.hisBabiesStuff').css('color','light blue');
    $this.has('.herBabiesStuff').css('color','pink');
}

The point isn't the actual code, but the use of $(this) when it is used more than once/twice/three times or more.

Am I better off performance-wise using example two than example one (maybe with an explanation why or why not)?

EDIT/NOTE

I suspect that two is better one; what I was a little fearful of was peppering my code with $this and than inadvertently introducing a potentially difficult-to-diagnosis bug when I inevitably forget to add the $this to an event handler. So should I use var $this = $(this), or $this = $(this) for this?

Thanks!

EDIT

As Scott points out below, this is considered caching in jQuery.

http://jquery-howto.blogspot.com/2008/12/caching-in-jquery.html

Jared

Yes, definitely use $this.

A new jQuery object must be constructed each time you use $(this), while $this keeps the same object for reuse.


A performance test shows that $(this) is significantly slower than $this. However, as both are performing millions of operations a second, it is unlikely either will have any real impact, but it is better practice to reuse jQuery objects anyway. Where real performance impacts arise is when a selector, rather than a DOM object, is repeatedly passed to the jQuery constructor - e.g. $('p').


As for the use of var, again always use var to declare new variables. By doing so, the variable will only be accessible in the function it is declared in, and will not conflict with other functions.


Even better, jQuery is designed to be used with chaining, so take advantage of this where possible. Instead of declaring a variable and calling functions on it multiple times:

var $this = $(this);
$this.addClass('aClass');
$this.text('Hello');

...chain the functions together to make the use of an additional variable unecessary:

$(this).addClass('aClass').text('Hello');