Function - JavaScript make value of variable public

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Here is excerpt from my larger JavaScript file:

function dashboardConfig()
{
    $(window).on( resize , function () {

        var viewport = {
            width : $(this).width(),
            height : $(this).height()
        };

        el.siteContainer.css(
        {
            marginTop : (viewport.height - 652) / 2
        });

        el.dashboardSlide.css(
        {
            marginLeft : (viewport.width - 1024) / 2,
            marginRight : (viewport.width - 1024) / 2
        });

        //Calculate how many nav elements
        el.navElements.each(function(i)
        {           
            el.dashboard.css(
            {
                width : viewport.width * (i + 1)
            });

            $(this).click(function()
            {
                //HERE IS THE VARIABLE I WOULD LIKE TO USE
                var dashboardSlidePosition = viewport.width * i;

                el.navElements.removeClass( active );
                $(this).addClass( active );

                el.dashboard.animate(
                {
                    left : -dashboardSlidePosition
                },500, function()
                {
                    el.dashboard.css(
                    {
                        left : -dashboardSlidePosition
                    });
                });
            });
        });

        //I WANT TO PERFORM ANOTHER FUNCTION HERE AND HAVE IT USE THE VALUE OF dashboardSlidePosition


    }).trigger( resize );
}

I want to know how I can pass the value of the variable, dashboardSlidePosition, to another function. Please can anyone explain how?

Many thanks in advance.

Answers

You can declare it at the outer edge of your scope. Make sure to give it an initial value so that you don t try to use it before it has been set properly.

function dashboardConfig()
{
    var dashboardSlidePosition = null;

    function anotherFunction() {
        if (dashboardSlidePosition != null) {
            // ...
        }
    }

    $(this).click(function()
    {
        dashboardSlidePosition = viewport.width * i;
    }
}

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/11167623/javascript-make-value-of-variable-public

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils