1

I'm new to jQuery and I know this is probably super easy. I wanna get the returned value from a callback function in an event. Code is here:

$('.hintItem').on('mouseenter', function(e){
     changeItemStyle(e);
     var hintItemIndex = $(this).index();
     return hintItemIndex;
});

I want to grab the value of hintItemIndex and store it to a new variable. Could anyone kindly help me?

2
  • 3
    That is not the way jquery callbacks work (you can't get the return value), explain your use case and perhaps we can suggest an alternative approach. Commented Feb 19, 2016 at 19:37
  • What's stopping you from storing it in a variable? What does that have to do with returning a value? Commented Feb 19, 2016 at 19:37

2 Answers 2

2

Try this:

var hintItemIndex;
$('.hintItem').on('mouseenter', function(e){
     changeItemStyle(e);
     hintItemIndex = $(this).index();
});

Basically, you define a variable outside the fuction and assign a value to it via the function.

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

3 Comments

Beware of accessing the variable before mouseenter event occurs
True @vinayakj, I definitely agree. I didn't put that in since I thought it wasn't in the scope of the OP. Should I?
Its ok, just wanted to warn OP, as OP didnt seems much experienced about callbacks. Answer is correct & I already given +1.
0

Try following function.

function getHintItemIndex() {
    var retVal;
    $('.hintItem').on('mouseenter', function(e){
     changeItemStyle(e);
     var hintItemIndex = $(this).index();
     return hintItemIndex;
     });
    return retval;
}

var retVal = getHintItemIndex();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.