King Kong
King Kong

Reputation: 2915

Event binding issue in jquery

  <div id="parent">
    <div id="children">
    </div>
  </div>

And if we bind both parent and children with same events like :

     $("#parent").live({ mouseenter : Infocus , mouseleave : Outfocus });
     $("#children").live({ mouseenter : Infocus , mouseleave : Outfocus });

Now my problem is when i get my mouse over to the children the parent is also highlighted, Can anybody tell me whats going on here?

Upvotes: 2

Views: 72

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

You've to use stopPropagation() for prevent event follow.

function Infocus(e) {
  e.stopPropagation();
  // your code
}

function Outfocus(e) {
  e.stopPropagation();
  // your code
}

Read about .stopPropagation()

You can do something like this: (may be not satisfactory)

$("#parent").live({
    mouseenter: Infocus,
    mouseleave: Outfocus
});
$("#children").live({
    mouseenter: Infocus,
    mouseleave: Outfocus
});

function Infocus(e) {
    if(this.id == 'parent') {
        $(this).css('background', 'yellow');
    } else if(this.id == 'children') {
        $(this).css('background', 'green');
        $(this).parent().trigger('mouseleave')
    }
}

function Outfocus(e) {
    if(this.id == 'parent') {
        $(this).css('background', 'transparent');
    } else if(this.id == 'children') {
        $(this).css('background', 'transparent');
        $(this).parent().trigger('mouseenter')
    }
}

DEMO

Upvotes: 2

Alexander
Alexander

Reputation: 23537

Even if the other answer is accurate in a sense. I think your problem is another one. What I think you are doing is highlighting on mouseenter and removing the highlighting on mouseleave but what is actually happening is different.

You never leave #parent when moving over #children. In a image if you move your mouse from left (1) to right (5) these are the triggered events:

                +-----------------------------------+
                |#parent                            |
                |                                   |
                |                                   |
                |          +-------------+          |
                |          |#children    |          |
                |          |             |          |
          (1)   |    (2)   |     (3)     |   (4)    |   (5)
                |          |             |          |
                |          |             |          |
                |          +-------------+          |
                |                                   |
                |                                   |
                |                                   |
                +-----------------------------------+
  1. nothing.
  2. #parent.mouseenter
  3. #children.mouseenter
  4. #children.mouseleave
  5. #parent.mouseleave

If this is the case then you need to modify your highlighting logic.

Upvotes: 2

Related Questions