1

I have the following statement in document.ready function:

  if($("sidebar ").html().trim().length == 0)
  {
    $("sidebar").append("<p>&nbsp;&nbsp;&nbsp;The sides..</p>"); 
  };

It works fine in IE 9 but as soon as I select IE 8 (browser and document standard), the script stops working and gives the following error:

SCRIPT5007: Unable to get value of the property 'trim': object is null or undefined 
application-e51c9eee7d22e9644481115dc1fedd5f.js, line 7 character 17578

I looked at the .js in debug mode and see that my statement above is transformed to:

$("sidebar ").html().trim().length==0&&$("sidebar").append("<p>&nbsp;&nbsp;&nbsp;The sides..</p>")

How do I prevent this error? Please note that I do see that the node is present in the rendered page.

I thought that maybe just having reference to shiv5.html may not be sufficient to take care of the IE idiosyncrasies. So, I have added modernizr.js via sprockets and I have added class="no-js" in my layout. Still no luck in IE <9.

What am I missing? What else can I do to get the favor of Microsoft overlords?

Tabrez
  • 3,424
  • 3
  • 27
  • 33

2 Answers2

5

According to MDN, trim isn't available in IE < 9.

You could use $.trim instead:

if($.trim($("sidebar ").html()).length == 0)
{
  $("sidebar").append("<p>&nbsp;&nbsp;&nbsp;The sides..</p>"); 
} // <-- Don't want a semicolon here.

The MDN article lists an alternative if you don't want to find all the instances of trim and correct them. You could use the following to create .trim if it's not natively available:

if(!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g,'');
  };
}
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • Thanks Andrew! That solved the issue with trim. But IE 8 still complains about the overall snippet of code. Now it is complaining about an "unexpected call" when it hits "append". Any suggestions? Here is the actual error: SCRIPT65535: Unexpected call to method or property access. application-49b3f7c89f7bb90bcdd86761195a59d1.js, line 6 character 15114 – Tabrez Dec 21 '11 at 22:21
  • Andrew - yes, the same piece of code. But I think I figured out the issue. Apparently it was because my node was called sidebar. I just changed it to a
    with class and id of sidebar, made appropriate changes to the css and js, and bam it worked! Thanks for providing the trim solution. That was a tough nut to crack!
    – Tabrez Dec 21 '11 at 22:35
0

Check out this thread. After a quick search it seems that many people are experiencing issues with trim.

Community
  • 1
  • 1
Matt K
  • 6,620
  • 3
  • 38
  • 60