I want to have a single script file for every page, which has scripts which may or may not be required for that particular page. On my homepage I have this script:
$(function () {
var $select = $('#select');
var $window = $(window);
var isFixed = false;
var init = $('#select').offset().top;
$window.scroll(function () {
var currentScrollTop = $window.scrollTop();
if (currentScrollTop > init && isFixed === false) {
isFixed = true;
$select.css({
top: 0,
position: 'fixed'
});
console.log("fixed");
} else if(currentScrollTop <= init && isFixed === true) {
isFixed = false;
$select.css('position', 'relative');
console.log("unfixed");
}
});
$("#scroll").click(function () {
$('html, body').animate({
scrollTop: $(".jumbo").offset().top + $(".jumbo").height()
}, 300);
});
});
However when this runs on the homepage (which doesnt have the #select element) I get this error and breaks my script:
Uncaught TypeError: Cannot read property 'top' of undefined
How can I get it to not cause errors if that script isnt required on that particual page without having to load it in its own file?
Should I have it call the function on page load?