Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match event.target with existing jQuery object

How can I do that?

event.target returns a HTML object,

and my element is a jQuery object.

Is there a better way to find out if event.target = my_jquery_object, besides comparing IDs or classes?

I want to make sure that it's the same object, not just a element with a similar class...

I tried with $(event.target) !== the_element and it fails

the_element is defined at the begining as $('.something', $(this))


What I am trying to do is to make a box close when the user clicks outside of it, but with the condition that the click wasn't made on the link that opened the box in the first place.

So I have this:

$(document).click(function(event){
  if(($(event.target).parents().index(box) == -1) 
    && box.is(':visible')){
      close(); 
  }

});

And I want to add another condition that verifies that the click wasn't made on the link that opened the box.

This works, but I don't like it:

if($(event.target).attr('id') != the_element)

:)

like image 862
Alex Avatar asked Nov 06 '11 14:11

Alex


People also ask

How do you call one event from another event in jQuery?

$('#b1'). on('click', function(){ $('#select_item'). trigger('change'); }); $('#select_item'). on('change', function(){ var jbyr = $(this).

Is event target deprecated?

Obsolete This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time.

What is jQuery event target?

The event. target property returns which DOM element triggered the event. It is often useful to compare event. target to this in order to determine if the event is being handled due to event bubbling.

What is the use of .on in jQuery?

The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree.


2 Answers

You can get the actual DOM element from the jQuery using .get(0) or simply the_element[0]. It would probably be better to check with jQuery, though.

if (the_element.is(event.target))
{
    ...
}

Using your example:

$(document).click(function(event){
  if (the_element.is(event.target)) {
      return false;
  }
  if(($(event.target).parents().index(box) == -1) 
    && box.is(':visible')){
      close(); 
  }

});
like image 98
tvanfosson Avatar answered Oct 31 '22 19:10

tvanfosson


Try -

if(event.target === the_element[0])

the_element[0] should unwrap your jQuery object and return a 'normal' DOM object, you can then compare it against the DOM object returned by event.target.

like image 37
ipr101 Avatar answered Oct 31 '22 19:10

ipr101