I have some javascript that was written years back. I've just noticed it's throwing up errors in the console on every page the object isn't included on. I get errors like...
Cannot read property 'top' of undefined TypeError: Cannot read property 'top' of undefined
and
Uncaught TypeError: Cannot read property 'top' of undefined at placeLines (main.js:276) at HTMLDocument. (main.js:299) at j (jquery-3.1.1.min.js:2) at k (jquery-3.1.1.min.js:2)
The javascript I'm running is as follows:
$(function(){
placeLines = function(){
for(i=0; i<=9; i++){
var Dy = $('.ball-container'+i).position().top - $('.ball-container'+(i+1)).position().top;
var Dx = $('.ball-container'+(i+1)).position().left - $('.ball-container'+i).position().left;
var length = Math.sqrt(Dy*Dy + Dx*Dx);
var angle = Math.atan2(Dy, Dx) * (-1);
var containerHeight = $('#animated-line > .inner').height();
var transform = 'rotate('+angle + 'rad)';
$('.line'+i).css({
'transform': transform
})
var offsetTop = $('.ball-container'+i).offset().top +6;
var offsetLeft= $('.ball-container'+i).offset().left +6;
$('.line-box'+i).css({
'width': length +'px'
}).offset({
left: offsetLeft,
top: offsetTop
});
}
};
$(document).ready(function(){
placeLines();
});
$(window).resize(function(){
console.log('resizing');
placeLines();
});
});
How can I stop these errors, can I check if the object is on the page before running the script or something like that? The parent/containing div is animated-line
.
Thanks in advance.