JMWalker
JMWalker

Reputation: 95

How can I get the value returned by a function triggered by a mouse event in JQuery

I have the html code below:

<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>

I have the following jQuery code:

$("div").on("mouseenter", function (){
          myidx = $(this).index();
          return myidx;
});

var x = y // The value myidx;

I want to assign the output of the function executed on mouseenter which is the value of myidx to var x. So that: var x = the value of myidx.

I have tried my experiments and have done a lot of research but I've not found a way of accessing the results returned by a function inside the jquery method "mouseenter". Please advice.

Upvotes: 0

Views: 82

Answers (4)

JMWalker
JMWalker

Reputation: 95

First define variable x, which will be standby in-case the mouseenter event is triggered so that the value of $(this).index(); will be assigned to it.

Second, setting the var x to global by removing the var before x will make it accessible outside the function that generated that value.

var x;

$("div").on("mouseenter", function (){
   x = $(this).index();
});

Now var x will output 6 in your case incase you alert x anywhere in your js file.

Upvotes: 0

Quentin
Quentin

Reputation: 944320

You can't get the return value since you didn't call the event handler function.

You could assign the value to a global (which you are doing with myidx), but then you would have to wait until the event had happened before using it.

You couldn't use the value from the event between assigning the event handler and the event happening.

Upvotes: 1

bln
bln

Reputation: 320

try

var x;
$("div").on("mouseenter", function (){
      myidx = $(this).index();
      x = myidx;
});

Upvotes: 0

Vigneswaran Marimuthu
Vigneswaran Marimuthu

Reputation: 2532

Use like below to update x;

var x;

$("div").on("mouseenter", function (){
    x = $(this).index();
});

Upvotes: 0

Related Questions