JQuery.focusOut () conditional action dependent on next selected item

I have a table cell with text input #usernameInput and link #saveLink . Using jQuery I have a function assigned to the click event #saveLink .

What I'm trying to achieve when: #usernameInput loses focus, I want to hide it. If he does not lose focus on #saveLink . In other words, if the user clicks anywhere other than #saveLink , I want to hide #usernameInput , otherwise call the click event on #saveLink .

I have no problem handling $('#usernameInput').focusout() , but I can't get it to determine if the save link was clicked.

Here is what I still have.

 <script type="text/javascript"> $('#usernameInput').focusout(function () { if (!$('#saveLink').is(':focus')) { $('#usernameInput').hide(); } return; });</script> 
+4
source share
2 answers

What I'm trying to achieve is when "#usernameInput" loses focus I want to hide it. If he does not lose focus to "#saveLink". In other words, if the user clicks anywhere other than '#saveLink' I want to hide '#usernameInput', otherwise the click event '#saveLink' is raised.

Perhaps you could bind the event to the body and just check e.target

 $("body").click(function(event){ if(!$(event.target).is("#saveLink")){ $("#usernameInput").hide(); } }); 

disclaimer , it's just a pseudo-code at the moment ... update a bit.

+5
source

I'm not sure if this is new, but today I found a better way (3.5 years later): event.relatedTarget is the element that you actually clicked.

 $elementLosingFocus.focusout(function (event) { var $elementYouAreTesting; $elementYouAreTesting = $("#whatever"); if (elementYouAreTesting[0] === event.relatedTarget) { // you clicked the element you were testing! } else { // you clicked something else } }); 
+1
source

Source: https://habr.com/ru/post/1344027/


All Articles