简体   繁体   中英

How to Detect Previous Element on Hover In

Can you please take a look at this demo and let me know how can I detect the id 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> 

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM