3

My parent DIV will have many clickable children, so using event delegation I'm trying to capture both the childrens click and hover events on the parent DIV as they bubble up.

Now the click event bubbles fine, but I can't seem to capture the hover event. Anyone know why?

Please don't tell me the hover event doesn't bubble :)

HTML:

<div id="theParent">

    <a href="#">Clicked 1</a>
    <a href="#">Clicked 2</a>
    <a href="#">Clicked 3</a>
    <a href="#">Clicked 4</a>
    <a href="#">Clicked 5</a>

</div>

jQuery:

$('#theParent').click(captureEvent).hover(captureEvent,captureEvent);

var captureEvent = function(e){

    console.log(e.target);

};
Steve
  • 3,483
  • 5
  • 21
  • 20
  • Wouldn't hovering over an `a` tag mean you aren't hovering over the `div`? Because it doesn't bubble, you would need to check if the div or any of its children are being hovered, a simple recursive function would do the trick nicely. I post this as a comment, because I'm not sure this is the answer to your question (as I don't quiet understand the question) – Jess Jul 12 '11 at 08:54
  • 1
    I would have thought that if you hover over an A tag then you're also hovering over the parent DIV. – Steve Jul 12 '11 at 08:57
  • @mazzzzz according to [this](http://stackoverflow.com/questions/5574207/javascript-which-events-do-not-bubble) mouseenter and mouseleave events don't bubble and as jQuery's hover is a shortcut for mouseenter and mouseleave, then I can see why the hover isn't bubbling/firing on the parent. – Steve Jul 12 '11 at 09:19
  • Yeah, think of them as completely different boxes, don't think of the nesting, and it makes more sense. – Jess Jul 12 '11 at 09:50

1 Answers1

0

Try defining captureEvent before using it — seems to work: http://jsfiddle.net/rEzSd/1/ . The target for the hover will however be a link if all space of #theParent is occupied by links. I've added some padding to make that clear.

polarblau
  • 17,649
  • 7
  • 63
  • 84
  • Sorry, I don't see the hover event being captured for each link. The hover is firing when you mouseover the DIV but not the links. – Steve Jul 12 '11 at 09:12
  • If you remove the padding you should get the hover over the links again. – polarblau Jul 12 '11 at 09:20
  • That's true, but for design reasons there needs to be padding around the links. I was hoping that when the user moves the mouse over the div and then the link that both the div and A hover would fire. Unfortunately I think I've since discovered that the mouseenter and mouseleave events don't actually bubble. – Steve Jul 12 '11 at 09:44