Sharjil Khan
Sharjil Khan

Reputation: 43

Jquery : How to trigger a click event when input focus is enable

I have an input field. On its focusin event I am opening a tooltip and on its focuout I am closing the tooltip. But now I am having a link on tooltip and what I want to do to make that link clickable. But when I start focusing input and go to that tooltip link and try to click than the input's focusout event gets called first and the tooltip gets closed. So I was unable to click that link. Here is my code :

html:

<div class="block"><input type="text" class="field-input"/><div class="tooltip">
<a href="#">tooltip link</a></div>

css:

.block{position:relative;}.tooltip{position:absolute;right:0;display:none;bottom:0;}

jquery:

$('.field-input').on('focusin', function(){
$('tooltip').show();
});
$('.field-input').on('focusout', function(){
    $('tooltip').hide();
});
$('.tooltip a').on('click', function(){
    ... do something
});

Upvotes: 0

Views: 2838

Answers (2)

luiscrjr
luiscrjr

Reputation: 7268

You can use relatedTarget to capture the element that is receiving the focus, and hide tooltip only if the clicked element is not the tooltip anchor.

From the docs:

The MouseEvent.relatedTarget read-only property is the secondary target for the event, if there is one. That is:

focusout: The EventTarget receiving focus

Something like that:

$('.field-input').on('focusout', function(e){
    var tooltipHolder = $('.tooltip');
    var tooltipAnchor = tooltipHolder.find('a');
    if (e.relatedTarget !== tooltipAnchor[0]) tooltipHolder.hide();
});

Upvotes: 0

Sergio Alen
Sergio Alen

Reputation: 724

You could remove the focusout event binding when the mouse enters the tooltip and add it back when the mouse leaves:

$('.tooltip').on({
  mouseenter: function(){
    $('.field-input').off('focusout');
  },
  mouseleave: function(){
    $('.field-input').on('focusout', function(){
      $('.tooltip').hide();
    });
  }
});

Upvotes: 2

Related Questions