1

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?

1 Answer 1

1

You can use the length property to check if an element exists:

var init = $select.length ? $select.offset().top : 0;

This will return 0 if the element is not present, otherwise its top offset.

Sign up to request clarification or add additional context in comments.

1 Comment

.length is the way to go! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.