Binding event handlers to specific elements, using bubbling (JavaScript/jQuery)

Posted by Bungle on Stack Overflow See other posts from Stack Overflow or by Bungle
Published on 2010-03-07T22:54:16Z Indexed on 2010/03/07 23:11 UTC
Read the original article Hit count: 365

I'm working on a project that approximates the functionality of Firebug's inspector tool. That is, when mousing over elements on the page, I'd like to highlight them (by changing their background color), and when they're clicked, I'd like to execute a function that builds a CSS selector that can be used to identify them.

However, I've been running into problems related to event bubbling, and have thoroughly confused myself. Rather than walk you down that path, it might make sense just to explain what I'm trying to do and ask for some help getting started. Here are some specs:

  • I'm only interested in elements that contain a text node (or any descendant elements with text nodes).
  • When the mouse enters such an element, change its background color.
  • When the mouse leaves that element, change its background color back to what it was originally.
  • When an element is clicked, execute a function that builds a CSS selector for that element.
  • I don't want a mouseover on an element's margin area to count as a mouseover for that element, but for the element beneath (I think that's default browser behavior anyway?).

I can handle the code that highlights/unhighlights, and builds the CSS selector. What I'm primarily having trouble with is efficiently binding event handlers to the elements that I want to be highlightable/clickable, and avoiding/stopping bubbling so that mousing over a (<p>) element doesn't also execute the handler function on the <body>, for example. I think the right way to do this is to bind event handlers to the document element, then somehow use bubbling to only execute the bound function on the topmost element, but I don't have any idea what that code looks like, and that's really where I could use help.

I'm using jQuery, and would like to rely on that as much as possible.

Thanks in advance for any guidance!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery