3

2015 Note: Everyone should go look through their old questions and be encouraged by how far they've come. There are so many things wrong with this code – it's wonderful.

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");
});
1
  • Can you separate the statements to see which one causes the error? Commented Aug 11, 2010 at 10:53

2 Answers 2

2
  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"); 
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, interesting - though I did try &&. JSLint didn't say anything about this.
2

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.