A Quick Quiz using jQuery .data()

Monday, March 18, 2013

Given this markup:

<div id="special" data-timeOut="3">
    
</div>

And this script code:

$(function() {
    var special = $("#special");
    var specialData = special.data();

    for (var p in specialData) {
        if (specialData.hasOwnProperty(p)) {
            special.text(p);
        }
    }
});

Answer the following questions:

Question #1

What output will appear when executing the code on Chrome or IE10?

a) timeOut

b) timeout

c)    (nothing)

d) ice cream

Question #2

What output will appear when executing the code on IE9?

a) timeOut

b) timeout

c)  (nothing)

d) yellow pencil

Let's change data-timeOut to data-time-out:

<div id="special" data-time-out="3">
    
</div>

Question #3

What output will appear when executing the code on IE 10, IE9, or Chrome?

a) timeOut

b) timeout

c)    (nothing)

d) whale teeth

Answers

1: B

2: C

3: A

Moral of the Quiz

Always use the data-some-name style, which gives you camel cased names in JavaScript (someName).

Never use camel case in the data- attribute itself.

RTFM, particularly the section titled "The algorithm for getting the list of name-value pairs".


Comments
gravatar Andrew Robinson Monday, March 18, 2013
I have been bitten by this myself but landed on data-somename which gives JavaScript names of "somename". I can now avoid thinking about the translation between dashes and camel casing but it is nice to know the rules.
gravatar Kim Tranjan Monday, March 18, 2013
Thank you!
gravatar Ryan Cromwell Tuesday, March 19, 2013
Seems the second - isn't entirely necessary. It's the caps O that kills it based on this fiddle. http://jsfiddle.net/asDV4/3/ Here's the section of the spec that denotes hyphens becoming camel cased: http://www.whatwg.org/specs/web-apps/current-work/#custom-data-attribute
gravatar Scott Allen Tuesday, March 19, 2013
@Ryan - Yes, thanks. That was the point of the post :)
gravatar nazihah Thursday, March 28, 2013
Can u give example of a quiz made with jQuery, without server-side processing of the results? After answering the questions, the result appears instantly. :)
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!