Javascript

Useful HTML-, CSS- and JavaScript Tools and Libraries

Advertisement in Useful HTML-, CSS- and JavaScript Tools and Libraries
 in Useful HTML-, CSS- and JavaScript Tools and Libraries  in Useful HTML-, CSS- and JavaScript Tools and Libraries  in Useful HTML-, CSS- and JavaScript Tools and Libraries

Front-end development is a tricky beast. It’s not difficult to learn, but it’s quite difficult to master. There are just too many things that need to be considered; too many tweaks that might be necessary here and there; too many details to make everything just right. Luckily, developers and designers out there keep releasing useful tools and resources for all of us to learn, improve our skills and just get better at what we do. Such tools are valuable and helpful because they save our time, automate mundane tasks and hence help us focus on more important things.

Here at Smashing Magazine, we’re continuously searching for time-saving, useful HTML-, CSS- and JavaScript-resources for our readers, to make the search of these ever-growing tools easier. We hope that these tools will help you improve your skills as well as your professional workflow. A sincere thanks to all designers and developers who are featured in this round-up. We respect and appreciate your contributions to the design community.

HTML and CSS Tools

HTML Email Boilerplate
This website and its sample code creates a template of sorts, absent of design or layout, that will help you avoid some of the major rendering problems with the most common email clients out there. It also provides some helpful examples and snippets that will keep your email design rendering as true-to-form as possible.

Emailboiler in Useful HTML-, CSS- and JavaScript Tools and Libraries

Initializr
This tool creates a customizable template based on HTML5 Boilerplate. Decide whether you want sample content, choose between JavaScript and jQuery, and specify your compatibility and server configuration needs. You’ll get a template based on key features of Boilerplate to start your next project. You might want to check out The HTML5 Framework Generator as well.

Useful-resources-227 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Layer Styles
A nice simple tool for creating CSS in an intuitive way — very much like you would do with a graphics editor. The tool lets you add drop shadow, inner shadow, background, border and border radius and generates cross-browser CSS code.

Layerstyles in Useful HTML-, CSS- and JavaScript Tools and Libraries

Mobile Boilerplate
A template that creates rich and performant mobile Web apps. You can get cross-browser consistency among A-grade smartphones, and fallback support for legacy Blackberry, Symbian, and IE Mobile.

Useful-tools-124 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Kotatsu
A simple HTML table generator that helps you create a table and throw in row as well as column classes quickly and easily. And if you want a quick tool to generate lists, you might want to take a look at li maker.

Useful-resources-188 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Zen Coding
Zen Coding is an editor plugin for high-speed coding and editing. The core of this plugin is a powerful abbreviation engine which allows you to expand expressions (similar to CSS selectors) into HTML code.

Vogue
This tool reloads the style sheet (not the HTML) of a page in all browsers, and it can even be configured to reload a page automatically in multiple browsers at the same time. The tool doesn’t host your website but rather runs your website’s own local server. To use it, you just need to install NodeJS and npm.

Useful-tools-162 in Useful HTML-, CSS- and JavaScript Tools and Libraries

LiveReload
LiveReload applies CSS/JS changes to Safari or Chrome without reloading the page and reloads the page automatically once the HTML changes. Alternatively, take a look at Live.js, a library that makes sure that you’re always looking at the latest version of the page you’re working on, whether you are writing HTML, CSS or JavaScript.

Useful-tools-141 in Useful HTML-, CSS- and JavaScript Tools and Libraries

css-x-fire
This tool allows editing CSS properties in the IDE from Firebug CSS editor and also allows the developer to concentrate on CSS styling without having to refresh the browser.

Cssxfire in Useful HTML-, CSS- and JavaScript Tools and Libraries

Ffffallback
A bookmarklet that lets you test different font stacks to find the best result. It bascially scans the page’s CSS and creates a clone page where you can test and analyze different fallback fonts.

Useful-resources-199 in Useful HTML-, CSS- and JavaScript Tools and Libraries

LESS.app for Mac OS X
LESS extends CSS with variables, nested rules and operators. This app makes it very simple to use {Less} by automatically compiling *.less files into standard CSS.

Useful-tools-151 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Less-Boilerplate
Boilerplate CSS is written in Less and includes a CSS reset, CSS3 helpers, centered column blocks, and much more.

Useful-resources-138 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Needle v0.1a1
Needle is a handy tool you can use to test whether your CSS renders correctly by taking screenshots of portions of a website and comparing them with other screenshots. It also provides tools for testing calculated CSS values and the position of HTML elements.

Useful-res-101 in Useful HTML-, CSS- and JavaScript Tools and Libraries

inuit.css
A CSS framework that provides you with the best dev tips, tricks and practices in one handy file.

Useful-tools-111 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Spritemapper
This application merges multiple images into one and generates CSS positioning for the corresponding slices; by reducing the amount of images and better utilizing the connection, CSS spritemapping can reduce your website’s loading time.

Useful-resources-178 in Useful HTML-, CSS- and JavaScript Tools and Libraries

CSSsitemap System
David Leggett shares with us the code for a CSS-based sitemap that Andrew Maier and himself have created and are still working on. A set of tools for project documentation & UX designers is also coming up soon.

Useful-resources-151 in Useful HTML-, CSS- and JavaScript Tools and Libraries

CSS Stress Testing and Performance Profiling
Andy Edinborough shares the code he uses for his so-called ‘CSS Stress Test’ for almost all browsers.

Normalize.css
Normalize.css takes a slightly different approach to CSS resets. Rather than eliminating all browser defaults, Jonathan Neal and Nicolas Gallagher have taken the time to research how different browsers handle different bits of code and then kept the defaults that are useful. It saves you time as a designer, while also providing consistent results.

Normalizecss in Useful HTML-, CSS- and JavaScript Tools and Libraries

Holmes
The tool is a diagnostic CSS style sheet that highlights possibly invalid or erroneous mark-up. Just add a single class, and it will create a red border around errors, a yellow border around warnings and a gray border around deprecated styles. In addition to the downloadable CSS style sheet, there’s also a Holmes bookmarklet that lets you apply holmes.css to any page within your browser.

Useful-resources-195 in Useful HTML-, CSS- and JavaScript Tools and Libraries

CSS Crush
A CSS pre-processor that is familiar, convenient, intuitive, and much more — everything Pete Boere wants a pre-processor to be.

Useful-res-103 in Useful HTML-, CSS- and JavaScript Tools and Libraries

CSSPrefixer
CSSPrefixer helps you improve your workflow and saves you a lot of time while inserting all of the necessary CSS prefixes for various browsers.

Useful-resources-210 in Useful HTML-, CSS- and JavaScript Tools and Libraries

iOS Media Query Previewer
A very simple tool to preview how a particular website looks on an iPhone as well as iPad.

Useful-resources-150 in Useful HTML-, CSS- and JavaScript Tools and Libraries

CSS Pivot
Here you can add CSS styles to any website and share the result with a short, handy link.

PCSS
A PHP-driven CSS preprocessor that helps you unleash the CSS3 power with much less code and features like class nesting, server-side browser specifics, default unit and variables. The tool requires PHP5.

JavaScript Tools

Modernizr 2
Modernizr is a widely used open-source JavaScript library that helps you build HTML5 and CSS3-powered websites. With the second version of the tool, you can now combine feature detection with media queries and conditional resource loading. That gives you the power and flexibility to optimize for every circumstance. Developed by Paul Irish, Faruk AteÅŸ and Alex Sexton.

Modernizr in Useful HTML-, CSS- and JavaScript Tools and Libraries

yepnope.js
A conditional loader for your polyfills that is very fast and allows you to load only the scripts that your users actually need.

Useful-res-117 in Useful HTML-, CSS- and JavaScript Tools and Libraries

FitText
FitText is a jQuery plug-in for responsive and fluid layouts that resizes display text to fit the parent element. A good solution for creating headlines that look good on everything from a small mobile device to a 30-inch desktop display.

Useful-resources-189 in Useful HTML-, CSS- and JavaScript Tools and Libraries

jQuery Waypoints
Waypoints is a small jQuery plugin that makes it easy to execute a function whenever you scroll to an element.

Useful-res-109 in Useful HTML-, CSS- and JavaScript Tools and Libraries

jQuery Plugin Boilerplate
This boilerplate implements public and private methods, as well as public and private properties, making it very easy when building both simple and complex jQuery plugins.

Useful-res-110 in Useful HTML-, CSS- and JavaScript Tools and Libraries

ligature-js
This Java script lets you convert text patterns into common typographic ligatures by going through the text on a web page and inserting ligatures where appropriate.

Useful-res-112 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Placeholder jQuery Plugin/Polyfill
This jQuery plugin provides support for the new placeholder="" HTML5 form attribute in browsers that don’t natively support it (IE et al).

Useful-res-105 in Useful HTML-, CSS- and JavaScript Tools and Libraries

StronglyTyped
A JS library that allows you to specify strongly typed properties of various types (Boolean, Number, String, etc.) and constants (final properties in Java). It uses ES5 getters and setters and falls back to regular, loosely typed properties in non-supporting browsers.

Useful-tools-129 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Kaffeine
A set of extensions to the JavaScript syntax that attempts to make it nicer to use. It compiles directly into JavaScript that is very similar, readable and line for line equivalent to the input.

Useful-res-113 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Crossroads.js
A JS routing library inspired by URL Route/Dispatch utilities which are present on frameworks like Rails, Pyramid, Django, CakePHP, CodeIgniter, etc. It parses a string input and decides which action should be executed by matching the string against multiple patterns.

Useful-res-114 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Doctor JS
Doctor JS analyzes your JavaScript code and provides you with a complete analysis in JSON, whether you’re dealing with polymorphism, prototypes, exceptions or callbacks. Tell Doctor JS about it:

Useful-res-118 in Useful HTML-, CSS- and JavaScript Tools and Libraries

HEAD.js
A script that speeds up, simplifies and modernizes your site — a concise solution to universal issues. You can load scripts like images as well as use HTML5 and CSS3 safely.

Hivelogic
Posting your email address on a website is an easy way to get an inbox full of spam. This anti-spam email address enkoder helps protect email addresses by converting them into encrypted JavaScript code so only real people using real browsers will see them. An alternative, more robust solution is Mollom.

Useful-tool-screenshot-005 in Useful HTML-, CSS- and JavaScript Tools and Libraries

JavaScript Garden
A JS project that offers advice on avoiding common mistakes and subtle bugs, and lays down performance issues and bad practices that JavaScript programmers might run into on their journey to the depths of the language.

Useful-resources-206 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Syntaclet
By clicking on the Syntaclet bookmarklet, you can automatically see all language specific syntax colored with line numbers to all the code on the page.

Useful-resources-173 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Bookmarkleter
This tool creates bookmarklets from JavaScript code. It removes new lines, tabs, and optional spaces, URL-encodes special ASCII characters and places code in a wrapper function (if not done already).

Useful-resources-144 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Bookmarklet Crunchinator
This great tool helps you quickly create a bookmarklet from any JavaScript code and will automatically be wrapped in a function to make it bookmarklet-friendly.

Grids

The JavaScript Grid
A JavaScript-based grid overlay — just drag the snipplets into your bookmarks bar, open your URL and click the bookmark.

Useful-tools-164 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Grid Calculator
A calculator that helps you easily create your own grid and download it for either Adobe Illustrator or Photoshop.

Useful-tools-139 in Useful HTML-, CSS- and JavaScript Tools and Libraries

GridCalc
This easy-to-use grid calculator lets you download a configuration as a CSS file which you can use in your project by simply entering the desired width of your page and an aproximate range for your column and gutter width. The calculator then gives you all the possible combinations within the limits you entered and provides you with a nice visual representation of the results and how the grid can be used.

Useful-tools-169 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Modular Grid Pattern
This tool enables you to create a grid template for Photoshop and other image editing applications. Enter the baseline, the module’s width and height, the gutter width, and the number of modules (columns), and it gives you a custom pattern to import into Photoshop. A Photoshop extension is also available, and you can download a PNG or transparency map, too.

Useful-resources-193 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Susy
A Rails framework that enables you to create a completely custom grid based on your mark-up and designs. No more compromises because the grid framework you’re working with isn’t quite what you need, and no more spending hours tweaking things to get them just right so that the design works the way you want.

Useful-resources-209 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Griddle.it
A clean and simple way to help you align your layouts. All you need to do is put your dimensions after the URL provided to get a background guide image to work with in your browser. Grids are created on the fly, so any combination should work.

Useful-tools-167 in Useful HTML-, CSS- and JavaScript Tools and Libraries

Last Click

ASCII Pronunciation Rules for Programmers
Most programmers would recognize ASCII characters on a website and know how to use them in their own work. But how many know what to call all those characters? This article gives a pretty thorough rundown of common and not-so-common names for ASCII characters. It’s a useful guide if you’re ever at a loss when listening to another programmer speak about coding.

Asciicharacters in Useful HTML-, CSS- and JavaScript Tools and Libraries

Weave Silk
Is your desktop, motivation or even design work in need of something fresh, swirly and remarkable? Just weave some Silk! Yuri Vishnevsky created this experimental, magical interactive gimmick. You can spend minutes playing around with this little technique, based upon HTML5 Canvas: no Flash in use.

Useful-resources-232 in Useful HTML-, CSS- and JavaScript Tools and Libraries

From Me To You
No, this has nothing to do with CSS, HTML or JavaScript, but it is just remarkable. On his photography blog, Jamir collects scenes from around the world, memorable events, food, people and small personal universes. The interesting part is that the photos are animated (hence the name); they come to life using good old animated GIFs. Pay a visit to the article Positioning an animated gif over a jpg image. His short tutorial explains how to save on bytes when putting GIFs and JPEGs together, without losing too much quality.

Beautiful Woman in Useful HTML-, CSS- and JavaScript Tools and Libraries

Related Articles

You might want to take a look at our previous related articles:

(vf) (il)


© Smashing Editorial for Smashing Magazine, 2011. | Permalink | Post a comment | Smashing Shop | Smashing Network | About Us
Post tags: , , ,


Ten Oddities And Secrets About JavaScript

Advertisement in Ten Oddities And Secrets About JavaScript
 in Ten Oddities And Secrets About JavaScript  in Ten Oddities And Secrets About JavaScript  in Ten Oddities And Secrets About JavaScript

JavaScript. At once bizarre and yet beautiful, it is surely the programming language that Pablo Picasso would have invented. Null is apparently an object, an empty array is apparently equal to false, and functions are bandied around as though they were tennis balls.

This article is aimed at intermediate developers who are curious about more advanced JavaScript. It is a collection of JavaScript’s oddities and well-kept secrets. Some sections will hopefully give you insight into how these curiosities can be useful to your code, while other sections are pure WTF material. So, let’s get started.

Data Types And Definitions

1. Null is an Object

Let’s start with everyone’s favorite JavaScript oddity, as well known as it is. Null is apparently an object, which, as far as contradictions go, is right up there with the best of them. Null? An object? “Surely, the definition of null is the total absence of meaningful value,� you say. You’d be right. But that’s the way it is. Here’s the proof:

alert(typeof null); //alerts 'object'

Despite this, null is not considered an instance of an object. (In case you didn’t know, values in JavaScript are instances of base objects. So, every number is an instance of the Number object, every object is an instance of the Object object, and so on.) This brings us back to sanity, because if null is the absence of value, then it obviously can’t be an instance of anything. Hence, the following evaluates to false:

alert(null instanceof Object); //evaluates false

2. NaN is a Number

You thought null being an object was ridiculous? Try dealing with the idea of NaN — “not a numberâ€� — being a number! Moreover, NaN is not considered equal to itself! Does your head hurt yet?

alert(typeof NaN); //alerts 'Number'
alert(NaN === NaN); //evaluates false

In fact NaN is not equal to anything. The only way to confirm that something is NaN is via the function isNaN().

3. An Array With No Keys == False (About Truthy and Falsy)

Here’s another much-loved JavaScript oddity:

alert(new Array() == false); //evaluates true

To understand what’s happening here, you need to understand the concepts of truthy and falsy. These are sort of true/false-lite, which will anger you somewhat if you majored in logic or philosophy.

I’ve read many explanations of what truthy and falsy are, and I feel the easiest one to understand is this: in JavaScript, every non-boolean value has a built-in boolean flag that is called on when the value is asked to behave like a boolean; like, for example, when you compare it to a boolean.

Because apples cannot be compared to pears, when JavaScript is asked to compare values of differing data types, it first “coercesâ€� them into a common data type. False, zero, null, undefined, empty strings and NaN all end up becoming false — not permanently, just for the given expression. An example to the rescue:

var someVar = 0;
alert(someVar == false); //evaluates true

Here, we’re attempting to compare the number 0 to the boolean false. Because these data types are incompatible, JavaScript secretly coerces our variable into its truthy or falsy equivalent, which in the case of 0 (as I said above) is falsy.

You may have noticed that I didn’t include empty arrays in the list of falsies above. Empty arrays are curious things: they actually evaluate to truthy but, when compared against a boolean, behave like a falsy. Confused yet? With good cause. Another example perhaps?

var someVar = []; //empty array
alert(someVar == false); //evaluates true
if (someVar) alert('hello'); //alert runs, so someVar evaluates to true

To avoid coercion, you can use the value and type comparison operator, ===, (as opposed to ==, which compares only by value). So:

var someVar = 0;
alert(someVar == false); //evaluates true – zero is a falsy
alert(someVar === false); //evaluates false – zero is a number, not a boolean

Phew. As you’ve probably gathered, this is a broad topic, and I recommend reading up more on it — particularly on data coercion, which, while not uniquely a JavaScript concept, is nonetheless prominent in JavaScript.

I discuss the concept of truthy and falsy and data coercion more over here. And if you really want to sink your teeth into what happens internally when JavaScript is asked to compare two values, then check out section 11.9.3 of the ECMA-262 document specification.

Regular Expressions

4. replace() Can Accept a Callback Function

This is one of JavaScript’s best-kept secrets and arrived in v1.3. Most usages of replace() look something like this:

alert('10 13 21 48 52'.replace(/\d+/g, '*')); //replace all numbers with *

This is a simple replacement: a string, an asterisk. But what if we wanted more control over how and when our replacements take place? What if we wanted to replace only numbers under 30? This can’t be achieved with regular expressions alone (they’re all about strings, after all, not maths). We need to jump into a callback function to evaluate each match.

alert('10 13 21 48 52'.replace(/\d+/g, function(match) {
	return parseInt(match) < 30 ? '*' : match;
}));

For every match made, JavaScript calls our function, passing the match into our match argument. Then, we return either the asterisk (if the number matched is under 30) or the match itself (i.e. no match should take place).

5. Regular Expressions: More Than Just Match and Replace

Many intermediate JavaScript developers get by just on match and replace with regular expressions. But JavaScript defines more methods than these two.

Of particular interest is test(), which works like match except that it doesn’t return matches: it simply confirms whether a pattern matches. In this sense, it is computationally lighter.

alert(/\w{3,}/.test('Hello')); //alerts 'true'

The above looks for a pattern of three or more alphanumeric characters, and because the string Hello meets that requirement, we get true. We don’t get the actual match, just the result.

Also of note is the RegExp object, by which you can create dynamic regular expressions, as opposed to static ones. The majority of regular expressions are declared using short form (i.e. enclosed in forward slashes, as we did above). That way, though, you can’t reference variables, so making dynamic patterns is impossible. With RegExp(), though, you can.

function findWord(word, string) {
	var instancesOfWord = string.match(new RegExp('\\b'+word+'\\b', 'ig'));
	alert(instancesOfWord);
}
findWord('car', 'Carl went to buy a car but had forgotten his credit card.');

Here, we’re making a dynamic pattern based on the value of the argument word. The function returns the number of times that word appears in string as a word in its own right (i.e. not as a part of other words). So, our example returns car once, ignoring the car tokens in the words Carl and card. It forces this by checking for a word boundary (\b) on either side of the word that we’re looking for.

Because RegExp are specified as strings, not via forward-slash syntax, we can use variables in building the pattern. This also means, however, that we must double-escape any special characters, as we did with our word boundary character.

Functions And Scope

6. You Can Fake Scope

The scope in which something executes defines what variables are accessible. Free-standing JavaScript (i.e. JavaScript that does not run inside a function) operates within the global scope of the window object, to which everything has access; whereas local variables declared inside functions are accessible only within that function, not outside.

var animal = 'dog';
function getAnimal(adjective) { alert(adjective+' '+this.animal); }
getAnimal('lovely'); //alerts 'lovely dog';

Here, our variable and function are both declared in the global scope (i.e. on window). Because this always points to the current scope, in this example it points to window. Therefore, the function looks for window.animal, which it finds. So far, so normal. But we can actually con our function into thinking that it’s running in a different scope, regardless of its own natural scope. We do this by calling its built-in call() method, rather than the function itself:

var animal = 'dog';
function getAnimal(adjective) { alert(adjective+' '+this.animal); };
var myObj = {animal: 'camel'};
getAnimal.call(myObj, 'lovely'); //alerts 'lovely camel'

Here, our function runs not on window but on myObj — specified as the first argument of the call method. Essentially, call() pretends that our function is a method of myObj (if this doesn’t make sense, you might want to read up on JavaScript’s system of prototypal inheritance). Note also that any arguments we pass to call() after the first will be passed on to our function — hence we’re passing in lovely as our adjective argument.

I’ve heard JavaScript developers say that they’ve gone years without ever needing to use this, not least because good code design ensures that you don’t need this smoke and mirrors. Nonetheless, it’s certainly an interesting one.

As an aside, apply() does the same job as call(), except that arguments to the function are specified as an array, rather than as individual arguments. So, the above example using apply() would look like this:

getAnimal.apply(myObj, ['lovely']); //func args sent as array

7. Functions Can Execute Themselves

There’s no denying it:

(function() { alert('hello'); })(); //alerts 'hello'

The syntax is simple enough: we declare a function and immediately call it just as we call other functions, with () syntax. You might wonder why we would do this. It seems like a contradiction in terms: a function normally contains code that we want to execute later, not now, otherwise we wouldn’t have put the code in a function.

One good use of self-executing functions (SEFs) is to bind the current values of variables for use inside delayed code, such as callbacks to events, timeouts and intervals. Here is the problem:

var someVar = 'hello';
setTimeout(function() { alert(someVar); }, 1000);
var someVar = 'goodbye';

Newbies in forums invariably ask why the alert in the timeout says goodbye and not hello. The answer is that the timeout callback function is precisely that — a callback — so it doesn’t evaluate the value of someVar until it runs. And by then, someVar has long since been overwritten by goodbye.

SEFs provide a solution to this problem. Instead of specifying the timeout callback implicitly as we do above, we return it from an SEF, into which we pass the current value of someVar as arguments. Effectively, this means we pass in and isolate the current value of someVar, protecting it from whatever happens to the actual variable someVar thereafter. This is like taking a photo of a car before you respray it; the photo will not update with the resprayed color; it will forever show the color of the car at the time the photo was taken.

var someVar = 'hello';
setTimeout((function(someVar) {
	return function()  { alert(someVar); }
})(someVar), 1000);
var someVar = 'goodbye';

This time, it alerts hello, as desired, because it is alerting the isolated version of someVar (i.e. the function argument, not the outer variable).

The Browser

8. Firefox Reads and Returns Colors in RGB, Not Hex

I’ve never really understood why Mozilla does this. Surely it realizes that anyone interrogating computed colors via JavaScript is interested in hex format and not RGB. To clarify, here’s an example:


Hello, world! <script> var ie = navigator.appVersion.indexOf('MSIE') != -1; var p = document.getElementById('somePara'); alert(ie ? p.currentStyle.color : getComputedStyle(p, null).color); </script>

While most browsers will alert ff9900, Firefox returns rgb(255, 153, 0), the RGB equivalent. Plenty of JavaScript functions are out there for converting RGB to hex.

Note that when I say computed color, I’m referring to the current color, regardless of how it is applied to the element. Compare this to style, which reads only style properties that were implicitly set in an element’s style attribute. Also, as you’ll have noticed in the example above, IE has a different method of detecting computed styles from other browsers.

As an aside, jQuery’s css() method encompasses this sort of computed detection, and it returns styles however they were applied to an element: implicitly or through inheritance or whatever. Therefore, you would relatively rarely need the native getComputedStyle and currentStyle.

Miscellaneous

9. 0.1 + 0.2 !== 0.3

This one is an oddity not just in JavaScript; it’s actually a prevailing problem in computer science, and it affects many languages. The output of this is 0.30000000000000004.

This has to do with an issue called machine precision. When JavaScript tries to execute the line above, it converts the values to their binary equivalents.

This is where the problem starts. 0.1 is not really 0.1 but rather its binary equivalent, which is a near-ish (but not identical) value. In essence, as soon as you write the values, they are doomed to lose their precision. You might have just wanted two simple decimals, but what you get, as Chris Pine notes, is binary floating-point arithmetic. Sort of like wanting your text translated into Russian but getting Belorussian. Similar, but not the same.

More is going on here, but it’s beyond the scope of this article (not to mention the mathematical capabilities of this author).

Workarounds for this problem are a favorite on computer science and developer forums. Your choice, to a point, comes down to the sort of calculations you’re doing. The pros and cons of each are beyond the scope of this article, but the common choice is between the following:

  1. Converting to integers and calculating on those instead, then converting back to decimals afterward; or
  2. Tweaking your logic to allow for a range rather than a specific result.

So, for example, rather than…

var num1 = 0.1, num2 = 0.2, shouldEqual = 0.3;
alert(num1 + num2 == shouldEqual); //false

… we would do this:

alert(num1 + num2 > shouldEqual - 0.001 && num1 + num2 < shouldEqual + 0.001); //true

Translated, this says that because 0.1 + 0.2 is apparently not 0.3, check instead that it’s more or less 0.3 — specifically, within a range of 0.001 on either side of it. The obvious drawback is that, for very precise calculations, this will return inaccurate results.

10. Undefined Can Be Defined

OK, let’s end with a silly, rather inconsequential one. Strange as it might sound, undefined is not actually a reserved word in JavaScript, even though it has a special meaning and is the only way to determine whether a variable is undefined. So:

var someVar;
alert(someVar == undefined); //evaluates true

So far, so normal. But:

undefined = "I'm not undefined!";
var someVar;
alert(someVar == undefined); //evaluates false!

You can also check Mozilla's list of all reserved words in JavaScript for future reference.

Further Resources

(al) (il)


© Mitya for Smashing Magazine, 2011. | Permalink | Post a comment | Smashing Shop | Smashing Network | About Us
Post tags: , ,


Get element text, including alt text for images, with JavaScript

Sometimes I find myself wanting to get the text contents of an element and its descendants. There is a DOM method called textContent that can be used for this. There is also jQuery’s text() method. Unfortunately neither method returns what I want.

In both cases, elements that can have alt attributes are omitted from the returned string. In my opinion, alt text is the text content of an img, input[type=image] or area element and should be returned by methods like these. I also find it a bit weird that they return the contents of script elements.

Not having any luck finding a method that includes alternative text and omits script elements when getting text content, I wrote my own.

Read full post

Posted in .

Copyright © Roger Johansson



Validate URL syntax with JavaScript

Something that I initially thought would be simple turned into hours of googling for solutions. The problem? I wanted to use JavaScript to check if a URL uses valid syntax.

What I ended up doing is use js-uri to parse the URLs I want to check and then use a couple of regular expressions to check the syntax of the URL parts it returns.

Where I’m using this I’m not particularly interested in checking that the domain exists or verifying that the URL is live – I just want to check that the path, query, and fragment parts do not use characters other than those described in RFC 3986.

Read full post

Posted in .



Make links focusable (or use real buttons)

When creating functionality that depends on JavaScript, many use a simple link (a element) to create a trigger for the function – you click it and something happens.

That may be ok, though often it would be more appropriate to use <button type="button">Do something</button> or <input type="button" value="Do something" />.

What is not ok is inserting an a element without giving it a non-empty href attribute, i.e. <a href="#">Do something</a>. Without a non-empty href attribute, the “link� will not be focusable and cannot be activated from a keyboard.

Read full post

Posted in , , .



  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress