1

How can I update a variable outside of a function? For example I have this:

        var max_index = 0;

    //loop through the z-index's
    $(".widget_container").each(function(){
        if($(this).attr("z-index") > max_index){
            max_index = $(this).attr("z-index") + 1;
        }
    });

    alert(max_index);

The only problem with this is that max_index is always alerting 0. How can I have that update the max_index?

2 Answers 2

3

Yes, you can update the variable, it's accessible from the outer closure, the problem is that z-index is not an attribute, it is a CSS property, you can get it using the jQuery css function:

    var max_index = 0;

    //loop through the z-index's
    $(".widget_container").each(function(){
      if($(this).css('zIndex') > max_index){
        max_index = +$(this).css('zIndex') + 1;
      }
    });

    alert(max_index);

Notice that I use a plus sign before the addition, that is the unary plus operator, it converts the zIndex value to number, since this function returns strings, and if one of the operands of the + operator is a string, a concatenation is done ( "0" + 1 = "01" ).

Also note that the CSS properties that contain dashes, like background-color or font-size, are accessed removing the dash, and capitalizing the next word.

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

Comments

0

I think

$(this).attr("z-index") 

should be

$(this).css("z-index")

This returns a string

Use:

parseInt($(this).css("z-index"))

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.