简体   繁体   中英

How to check if user is focusing from a particular element to another element with Javascript?

How can I check if a user is focusing out of a particular element to another particular element? Something like this:

// If focusing out of inputA to inputB
if ($("#inputA").focusingTo("#inputB")) {
  // do something
}

 // When focus A $('#inputA').focus(function() { // if the mouse is over 'B' then show #message $('#inputB').mouseover(function() { // action $('#message').removeClass('hidden'); }); // else hide #message $('#inputB').mouseleave(function() { // action $('#message').addClass('hidden'); }); }); // if 'A' loses focus $('#inputA').blur(function() { // Clear Listeners $("#inputB").off("mouseover").off('mouseleave'); $('#message').addClass('hidden'); }); 
 .hidden { display:none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <input id="inputA" name="inputA" value="inputA" /> <span id="message" class="hidden">on B</span> </div> <div > <input id="inputB" name="inputB" value="inputB" /> </div> 

You just need to do the checks you want inside this handler. Notice the class allows you to attach this only to the elements you want.

 var previousFocus = null; $('.monitored').focus(function() { var previous = previousFocus ? 'object '+previousFocus : 'nowhere'; console.log('focused on ' + this.id + ' coming from ' + previous); previousFocus = this.id; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <input class="monitored" id="inputA" name="inputA" value="inputA" /> </div> <div > <input class="monitored" id="inputB" name="inputB" value="inputB" /> </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