I have a script that grabs the ‘id’ of a clicked ‘div’ and uses it as a variable, as below:
$(document).ready(function(){
$(".box").click(function(e){
var newvar = ("#" + $(this).attr("id") + "Contact");
alignPop();
if(status==0){
$("#popBG").css({
"opacity": "0.5"
});
$("#popBG").fadeIn("slow");
$(newvar).fadeIn("slow");
popupStatus = 1;
}
Now, so far everything is running as clockwork but when the script fires the function ‘alignPop()’, which is defined outside the brackets of the ‘click’ function it doesn’t recognize the newly defined variable ‘newvar’. The script would continue something like:
function alignPop(){
var popH = $(newvar).height();
var popW = $(newvar).width();
How come doesn’t the script recognize the variable later on in the script? Might it be because the entire script is loaded at once, before the variable is defined? Are there ways around this?
Thanks, and please keep the answer in simple English, as I’m new to this stuff!
The variable is not scoped correctly. Because it is declared within the
readyfunction, it is contained within the scope of that function and can’t be seen elsewhere in the script. If you were to, outside your function, put avar newvar;and inside thereadyfunction, remove thevaron the linenewvar = ("#" + $(this).attr("id") + "Contact");, you should be able to use it as a global variable.Code would look like: