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");
});
&& instead of & (unless it's meant for minimizing)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");
}
});
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With