1

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?

8
  • 4
    downvoter care to comment? Commented Aug 19, 2015 at 11:29
  • 2
    @Hacketo though much better than 80% of the questions here.... Commented Aug 19, 2015 at 11:33
  • 1
    It is not a duplicate of that question. Commented Aug 19, 2015 at 11:37
  • 1
    @GEspinha is there only one element that this affects? Commented Aug 19, 2015 at 11:39
  • 2
    @Popnoodles we can use a .each() loop and use the logic you proposed - ie loop through each obj and create a variable for each one Commented Aug 19, 2015 at 11:40

2 Answers 2

1

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

@GEspinha For clarity $('.obj').hover(function is the same as $('.obj').on('mouseenter mouseleave', function
I guess this solution is much simpler and easy to understand, thanks :)
1

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

2 Comments

may have to fix this reference
Btw this is not a re-use of obj_top variable. Only re-use of function

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.