Setting variables in jquery function

Go To StackoverFlow.com

0

In my init I have set some variables and one animate that uses those variables.


What if I want to use that same animate/variables in my clickSlide? http://jsfiddle.net/lollero/4WfZa/ ( This obviously wouldn't work. )

I could make it global http://jsfiddle.net/lollero/4WfZa/1/ ( by removing the var )


Question is: Is there a better way, or is this perfectly ok way of doing it?

2012-04-04 08:23
by Joonas


2

Put the variable outside the function and than get the value

var getWidth ;
var getHeight ;

$(function(){

    var slideBox = {

        gb: $('#box'),

        init: function() {

                sb = this,
                getBox = sb.gb,
                getWidth = getBox.width(),
                getHeight = getBox.height();
            getBox.animate({ marginLeft: '+='+getWidth }, 600 );

            $("#button").on("click", this.clickSlide);
        },

        clickSlide: function() {

            getBox.animate({ marginLeft: '+='+getWidth }, 600 );
        }
    };

    slideBox.init(); 
});

than make use in the function so that you can get the vlue in you clickside function

2012-04-04 08:26
by Pranay Rana
I would at least put them inside the ready event handler, so that they are not global. But in any case, this would allow to only have one slide box object - Felix Kling 2012-04-04 08:28


1

If you are gonna use them a lot, I would made them a property of the object.

2012-04-04 08:27
by Adrien Schuler
Global is global. How is this related to closures? Anyways, I think making them properties of the object is the best solution - Felix Kling 2012-04-04 08:28
You're right. I missed the point - Adrien Schuler 2012-04-04 15:54


0

Your variables seem unnecessary, you can access everything you need to like this: http://jsfiddle.net/4WfZa/6/. If you do need to store them you can always add them to the slideBox object and then populate them in init. This way the variables are stored against the object and can be used in any of the functions within it.

For a great article on javascript namespacing, including how to set up private and public variables see this article.

2012-04-04 08:45
by Jon
Ads