liveBook · Manning

Safe cross-browser fix

As explained in Secrets of the JavaScript Ninja, Second Edition

A cross-browser fix that resolves a browser-specific problem without adverse effects in other browsers or reliance on detection logic.

A safe cross-browser fix prevents a browser-specific failure without detection logic or side effects in other browsers. Aim for one behavior that works consistently across browsers. section 14.3.1

// ignore negative width and height values
if ((key == 'width' || key == 'height') && parseFloat(value) < 0)
  value = undefined;

This jQuery fix ignores negative width and height values in every browser, avoiding exceptions in affected Internet Explorer versions without changing other browsers’ behavior. section 14.3.1

A uniform restriction can also be worthwhile when a browser limitation makes an operation unreliable: jQuery rejects changing the type attribute of an input already in the DOM, using the same exception across browsers. This sacrifices an ability elsewhere for a consistent API, so weigh that tradeoff carefully. section 14.3.1

if (name == "type" &&
    elem.nodeName.toLowerCase()== "input" &&
    elem.parentNode)
  throw "type attribute can't be changed";

The check rejects attempts to change an input’s type attribute when it has a parent node. section 14.3.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines two safety criteria, demonstrates jQuery fixes, and flags the tradeoff of restricting all browsers.
Examples
Uses negative width and height values and attempts to change an input’s type attribute as examples.
What you can do after
Apply fixes that handle invalid inputs uniformly or enforce shared restrictions, weighing API consistency against lost capabilities.
How it connects
Links browser detection and feature detection to cross-browser compatibility and reusable JavaScript APIs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.