mattb
mattb

Reputation: 25

jQuery hover on the same element

With jQuery hover how do you check if you've just hovered on the same element again? Say I have two boxes and hover on box 1, then left, then come back and hover on that same box. I'd like to store the value of the initial hovered element (box 1) and then compare if it's the same when hovering back.

Thanks!!

Upvotes: 0

Views: 113

Answers (3)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

Try something like below,

var lastHovered = '';

$('#box1').hover(function () {
    if (lastHovered == 'box1') {
       alert('You have hovered on this already');
    }   
    lastHovered = 'box1';

    //Your stuff
}, function () {
    //mouse out stuff
});

$('#box2').hover(function () {
    if (lastHovered == 'box2') {
       alert('You have hovered on this already');
    }   
    lastHovered = 'box2';

    //Your stuff
}, function () {
    //mouse out stuff
});

Note: I have used 2 functions assuming that box1 hover and box2 hover has totally different functionalities... If not you can have it inside same function and use this.id to group them.. see below.

var lastHovered = '';

$('#box1, #box2').hover(function () {
    if (lastHovered == this.id) { //<-- used this.id instead of hard-coded value
       alert('You have hovered on ' + this.id + ' already');
    }   
    lastHovered = this.id; //<-- used this.id instead of hard-coded value

    //Your stuff
}, function () {
    //mouse out stuff
});

Upvotes: 2

DefyGravity
DefyGravity

Reputation: 6031

var lastHovered = null;
$('#selector1,#selector2,#selector3').hover(function (evt) {
    if(lastHovered && lastHovered === $(this).attr("id")){
//code for 're-hovering'
    }else{
//code for 'new hover'
    }
}, function (evt) {
    //mouse out stuff
    lastHovered  =  $(this).attr("id");
});

Upvotes: 0

GillesC
GillesC

Reputation: 10874

Use .data() http://api.jquery.com/data/ so on first hover in the callback do something like

if (!$(this).data('var')) {
    $(this).data('var','value');
} else {
    console.log($(this).data('var'));
};

Upvotes: 0

Related Questions