gespinha
gespinha

Reputation: 8497

Jquery multiple function with same variables

I have the following mouseenter/mouseleave function:

$('.obj').on('mouseenter', function(){
    var obj_top = $(this).offset().top,
        obj_max = obj_top + 10;
}).on('mouseleave', function(){
    var obj_top = $(this).offset().top,
        obj_max = obj_top + 50;
});

Since it all happens within the same object, is there anyway I can reuse the obj_top variable throughout the functions without having to duplicate it?

Upvotes: 1

Views: 76

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388446

You can't because those variables are local to the function scope in which they are declared unless you declare it in a shared scope.

But if you don't want to repeat it again then you can use a single event handler for both mouseenter and mouseleave and check the event.type to see which is the event that caused the trigger based on that decide on the value to be added to the obj_top to find out obj_max

$('.obj').hover(function (e) {
    var obj_top = $(this).offset().top,
        obj_max = obj_top + (e.type == 'mouseenter' ? 10 : 50);
});

Upvotes: 1

danielaKay
danielaKay

Reputation: 189

By moving it into a function?

$('.obj').on('mouseenter', function(){
    setVariables(this, 10);
}).on('mouseleave', function(){
    setVariables(this, 50);
});

setVariables = function(sourceElement, amount) {
    var obj_top = $(sourceElement).offset().top,
        obj_max = obj_top + amount;
}

EDIT: Arun P Johny is right, fixed the faulty "this" reference

Upvotes: 1

Related Questions