0

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!

2 Answers 2

1

The variable is not scoped correctly. Because it is declared within the ready function, 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 a var newvar; and inside the ready function, remove the var on the line newvar = ("#" + $(this).attr("id") + "Contact");, you should be able to use it as a global variable.

Code would look like:

var newvar;
$(document).ready(function () {
    $(".box").click(function(e){
        newvar = ("#" + $(this).attr("id") + "Contact");
        // ..
Sign up to request clarification or add additional context in comments.

1 Comment

@gdoron Showed relevant fixed code. And Matias No problem. Don't forget to mark as the correct answer on the right one. And welcome to StackOverflow :)
1

"How come doesn't the script recognize the variable later on in the script?"

Because "newvar" isn't in the scope of the alignPop function. You need to pass this variable as an argument. Try:

function alignPop(elem){
    var popH = $(elem).height();
    var popW = $(elem).width();
    ...
}

and call this function like that:

alignPop(newvar);

For a better performance you can pass elem as a jQuery object not a string.

Comments

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.