views:

32

answers:

2

This code works PERFECTLY in Firefox, and in IE the line ending 'negative'); breaks. I have no idea how to fix it! Argghhh!

$(".topline strong").digits().each(function () {
s = $(this),
c = "change";
if ($(s).hasClass(c) & $(s).text().replace(/%/gi, "") > 0) { $(s).addClass("positive"); }
if ($(s).hasClass(c) & $(s).text().trim().charAt(0) == "-") $(s).addClass("negative");
});
+2  A: 
  1. Please use && instead of & (unless it's meant for minimizing)
  2. String.trim isn't widely implemented yet. Use

    $(s).hasClass(c) && /^\s*-/.test($(s).text())
    

    instead.

I'd rather rewrite the code as:

$(".topline strong").digits().each(function() {
  var s = $(this);
  if (s.hasClass("change")) { // no need to $() an already $()-ed object.
    var value = parseFloat(s.text());
    if (value != 0)
      s.addClass(value > 0 ? "positive" : "negative"); 
  }
});
KennyTM
+1  A: 

Instead of .trim() you can use $.trim() like this:

$(".topline strong").digits().each(function () {
  var s = $(this), c = "change";
  if (s.hasClass(c) && s.text().replace(/%/gi, "") > 0) { s.addClass("positive"); }
  if (s.hasClass(c) && $.trim(s.text()).charAt(0) == "-") s.addClass("negative");
});

Also note the s changes, there's no need to clone it as another jQuery object each time, it already is one so use it :) As for the error: .trim() isn't in all browsers, this is why jQuery includes the $.trim() function (same reason it has $.inArray(), IE doesn't have .indexOf()).

Also when declaring variable use var, otherwise you're creating global variables.


As an aside for future readers of this, jQuery 1.4.3+ will use the native String.prototype.trim if it's available when calling $.trim().

Nick Craver