Variable Scope and load and $(document).ready

I’m doing a Helping Develop Tutorial, and they have a variable declared inside a function using

$(document).ready(somefunction(){}
someVariable = var slider_total = $("#slider > img").size();
StartSlider();
}

So SomeVariable just counts up all the images I have inside a div class. It then calls someVariable from another function.

I tried what I thought was the same thing, except instead of using $(document).ready, I had the StartSlider function called with a JavaScript onload event inside a html element, and I just declared someVariable inside of StartSlider, thinking everything would still be initialized onload.

I’m getting a slider_total is not defined error. So I’m just asking whats the difference between onload and $document).ready that one way works and the other way doesn’t.

Hi John,

You’ve got a couple issues with the code you posted:

$(document).ready(somefunction(){}  // 1. closing brace
someVariable = var slider_total = $("#slider > img").size();  // 2. var keyword in the middle of assignment
StartSlider();
}
  1. The closing brace would cause you problems - but this is probably a typo while typing out your example?

  2. You can’t put the var keyword in the middle of a statement like that, you’ll get a syntax error. You could do something like this instead:

var someVariable, slider_total;
someVariable = slider_total = $("#slider > img").size();

It’s also worth mentioning that you don’t actually need to wrap code in an onLoad or $(document).ready() call - if you include it just before the page’s closing tag it won’t be executed until the DOM is ready anyway.

Yeah, the closing brace was a typo. I probably didn’t know about the variable declaration thing. Thank you for the info.

I’m now using this tutorial as a better guideline.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.