Reputation: 6330
I am working on the demo below. How can I detect theid
of previous element when mouse hover over #box-5
?
For example I want to console log the id of the each div which the mouse moved in to the #box-5
$("#box-5").hover(function(){
console.log("Entering From ...")
}, function(){
});
body {
padding: 20px;
}
#box{
width:320px;
height:300px;
}
.map{
height:100px;
width:100px;
border:1px solid #ccc;
float:left;
}
#box-5{
background:khaki;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div id="box-1" class="map"></div>
<div id="box-2" class="map"></div>
<div id="box-3" class="map"></div>
<div id="box-4" class="map"></div>
<div id="box-5" class="map"></div>
<div id="box-6" class="map"></div>
<div id="box-7" class="map"></div>
<div id="box-8" class="map"></div>
<div id="box-9" class="map"></div>
</div>
Upvotes: 0
Views: 427
Reputation: 6025
Keep track of the last hovered element in a variable and update it every time one of these elements is hovered
$("#box-5").hover(function(){
console.log("Entering From ..." + last_box)
}, function(){
});
var last_box = null;
$('.map').hover(function(){
if($(this).attr('id') != 'box-5'){
last_box = $(this).attr('id');
}
})
body {
padding: 20px;
}
#box{
width:320px;
height:300px;
}
.map{
height:100px;
width:100px;
border:1px solid #ccc;
float:left;
}
#box-5{
background:khaki;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div id="box-1" class="map"></div>
<div id="box-2" class="map"></div>
<div id="box-3" class="map"></div>
<div id="box-4" class="map"></div>
<div id="box-5" class="map"></div>
<div id="box-6" class="map"></div>
<div id="box-7" class="map"></div>
<div id="box-8" class="map"></div>
<div id="box-9" class="map"></div>
</div>
Upvotes: 3
Reputation: 68665
You can store the hovered element's id in a separate variable and every time change it in the hover event handler function.
let hoveredId = 0;
$(".map").hover(function() {
this.id !== 'box-5' ? hoveredId = this.id
: console.log(`Entering from ${hoveredId}`);
}, () => {});
body {
padding: 20px;
}
#box {
width: 320px;
height: 300px;
}
.map {
height: 100px;
width: 100px;
border: 1px solid #ccc;
float: left;
}
#box-5 {
background: khaki;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div id="box-1" class="map"></div>
<div id="box-2" class="map"></div>
<div id="box-3" class="map"></div>
<div id="box-4" class="map"></div>
<div id="box-5" class="map"></div>
<div id="box-6" class="map"></div>
<div id="box-7" class="map"></div>
<div id="box-8" class="map"></div>
<div id="box-9" class="map"></div>
</div>
Upvotes: 0