0

I have a script like this:

var target = $('#box1, #box2, #box3, #boxn').find('.content p');
target.hover(function() {
    alert([the base element]);
})

I need to get the base element #box1 or #box2 or #box3 etc that contains the element that has the mouse over itself.

Is there a way to do this?

DaFois
  • 2,197
  • 8
  • 26
  • 43
  • Pass the event object, and retrieve `$(event.target).closest('[id^="box"]');`. – Teemu Dec 15 '19 at 18:22
  • what do you mean with "pass the event object", I don't get it... sorry – DaFois Dec 15 '19 at 18:24
  • Does this answer your question? [Getting the ID of the element that fired an event](https://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event) – Eldar Dec 15 '19 at 18:26
  • @eldar No, because my event is fired on the `p` element that is child of the box – DaFois Dec 15 '19 at 18:28
  • `target.hover(function(event$) { event$.currentTarget // <- this is what you seek. })` – Eldar Dec 15 '19 at 18:30
  • @DaFois Jquery passes the event object to the handler function, similar to events attached by native `addEventListener`, i.e. `target.hover(function(event) {...});`. – Teemu Dec 15 '19 at 18:30
  • @Eldar It looks like the events are attached to the `p` elements, which are also referred by `event.currentTarget`. – Teemu Dec 15 '19 at 18:33
  • @Teemu I simplified the id names but I don't have `box1` as real name... I need to get it from the script... – DaFois Dec 15 '19 at 18:39
  • @Teemu sorry it should be the target not current target. `target` is the original element that owns the event. – Eldar Dec 15 '19 at 18:39
  • @DaFois Then use event delegation (attach the listeners to "`#boxN`"s`), that way Eldar's comment would work. – Teemu Dec 15 '19 at 18:41
  • How many `#box` is there and what's their real Id ? – Thanh Trung Dec 15 '19 at 19:22

1 Answers1

1

jQuery event handlers have a general form that could handle what you're asking:

// `.hover()` is a helper for handling both `mouseenter` and `mouseleave`
$('#box1, #box2, #box3, #boxn').on('mouseenter mouseleave', '.content p', function(event) {
    // element that is currently the focus of the bubbled event;
    // usually the same as `this`, the element on which the event was triggered
    console.log(event.currentTarget);
    // element to which this handler is bound
    console.log(event.delegateTarget);
});

If set up this way, .delegateTarget would be the parent element you want.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62