Minimi Minimi - 5 months ago 8
Javascript Question

Javascript Printing variables to console in file as opposed to in function

I have a JS file where I initialize this variable:

var totalSlideNumber = $(".background").length;


in file scope. I then try to print it to console on the next line:

var totalSlideNumber = $(".background").length;
console.log($(".background").length);


But this always prints 0. When I print the same variable in a function I get 3:

function parallaxScroll(evt) {

console.log($(".background").length);
...


Why are the values different from file scope to function scope?

Answer

Why are the values different from file scope to function scope?

It's not a question of "file scope" and "function scope", it's simply that the value is changing between the time you first execute the code and the time you next execute the code.

Specifically, this code:

$(".background")

When that selector queries the DOM the first time, it doesn't find anything. So the number of results is 0. When you execute it again later, it does file matches. So the number of results is 3 in this case.

It sounds like the first time you're executing the code is before the DOM structure has fully loaded. So the elements you're looking for simply don't exist yet. You can wait until the DOM structure is loaded and ready by using a document.ready handler:

$(document).ready(function () {
    console.log($(".background").length);
});

Or, shorter:

$(function () {
    console.log($(".background").length);
});
Comments