I have an app.js file that contains all my JS for all site pages. Within the app.js file is a function for age. The function runs fine on the page with the class of '.age'. But what is the best approach to avoid this being run on all other pages?
var start = new Date('09/20/1991 06:00 AM');
var timer;
function age() {
var now = new Date();
var age = now.getTime() - start.getTime();
var year = (age / 31556926000);
document.getElementById('age').innerHTML = year.toFixed(9);
}
timer = setInterval(age, 1);
Thank you and sorry if this is a silly question.
You can check if the element exists and only then register the function:
let ageElement = document.getElementById('age');
// Check the age element exists
if(ageElement){
var start = new Date('09/20/1991 06:00 AM');
var timer;
function age() {
var now = new Date();
var age = now.getTime() - start.getTime();
var year = (age / 31556926000);
ageElement.innerHTML = year.toFixed(9);
}
timer = setInterval(age, 1);
}