I have a simple javascript/jquery task which runs on page load.
Nothing changes on the page when I click refresh - I'm just giving it some reasonable testing - however I noticed that sometimes one of the functions doesn't complete correctly.
Here are the functions:
$(document).ready(function () {
initialise();
load();
});
// 1. Cache the main selectors just in case the window is resized
function initialise() {
$banners = $("#header .banner");
}
// 2. Loop through each of the elements
function load() {
$banners.each(function () {
setBannerStyle($(this));
});
}
// 3. Add attributes to each of the banner elements
function setBannerStyle($selector) {
icon = $selector.find(".icon").first().length;
rows = getRows($selector.find(".message").first());
$selector.attr({
"data-icon": icon,
"data-rows": rows
});
}
// 4. Helper to do the workings out
function getRows($selector) {
var height = $selector.height();
var lineHeight = parseFloat($selector.css("line-height"));
var rows = Math.round(height / lineHeight);
return rows > 2 ? 2 : rows;
}
As you can see there is no complexity and the number of elements to loop through is rarely more than one.
However, on rare occasions the number of rows returns NAN. How can I ensure that a valid number is always returns (or at least improve the chance of it not happening). It currently fails about once in 10 on my quad core i5 processor.
To be clear, I don't wan't to set defaults when it fails - I want to try and stop it failing in the first place.
Any advice appreciated as I'm not too great with javascript.