0

I am using jQuery and want to store a list of hovered elements in an array. The code I am using is below (you can paste it into an empty html document to test it):

<div class="element" style="width:100px;height:100px;border:1px solid black;"></div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
var hovered = [];
$(document).ready(function(){
    $(".element").hover(function(){
        hovered.push($(this));
        console.log(hovered.indexOf($(this)));
    });
});
</script>

Whenever I hover over the div, -1 always gets logged to the console. Why is this and what is a potential workaround?

Adam Griffiths
  • 680
  • 6
  • 26
  • 60

2 Answers2

0

Change it to

hovered.push(this)

and

hovered.indexOf(this)
quirimmo
  • 9,800
  • 3
  • 30
  • 45
-1

You are creating two distinct jQuery objects, The one you push, and the one you pass to indexOf(..)

Change your code as follows:

$(document).ready(function(){
    $(".element").hover(function() {
        var $this = $( this );

        hovered.push( $this );

        console.log( hovered.indexOf( $this ) );
    });
}); 
elad.chen
  • 2,375
  • 5
  • 25
  • 37