Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - detect the click outside of input [duplicate]

<input id="ok" /> 

$('.hor-minimalist-a').on('blur','#ok',function(){

});

with this code above, i can handle events which fire If i leave the input field.

How can I detect if someone clicks outside of inputfield without coming to input. I mean the user never came to this input field before, so there was no focus at all.

$('.hor-minimalist-a').on('?','#ok',function(){
  ?
});
like image 559
doniyor Avatar asked Aug 06 '14 14:08

doniyor


People also ask

How to detect a click outside of an element with jQuery?

Answer: Use the event. target Property You can use the event. target property to detect a click outside of an element such as dropdown menu. This property returns the DOM element that initiated the event.

How do I detect a click outside an element?

So, for detecting a click outside an element, it would be best if you add a listener to the whole document element. Consequently, the main loop will go up the DOM from the clicked target element to search if the ancestor of that element belongs to the flyout container.

How do you close an element on click outside?

To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.


3 Answers

$(document).on('click', function(e) {
    if ( e.target.id != 'ok' ) {
        // you clicked something else
    }
});

That would capture any click except on the input, but why would you need it ?

To capture only clicks on .hor-minimalist-a and not the entire document, just replace document with that selector in the code above.

like image 98
adeneo Avatar answered Sep 30 '22 08:09

adeneo


How about:

$('.hor-minimalist-a').on('click',':not(#ok)',function(){

That'll register click events within .hor-minimalist-a but outside the input #ok

like image 39
tymeJV Avatar answered Sep 30 '22 07:09

tymeJV


There is a jquery plugin for that: http://benalman.com/code/projects/jquery-outside-events/examples/clickoutside/

like image 35
Leif Avatar answered Sep 30 '22 08:09

Leif