Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's live functionality without jQuery

I was wondering how to achieve jQuery's .live functionality with "traditional" JavaScript. I want something like $('a').live('mouseover', mouseover_func) to be written as usual JavaScript. But how?

like image 796
Rainer Zufall Avatar asked Feb 13 '11 16:02

Rainer Zufall


1 Answers

Bind a "mouseover" event handler to the <body> element. In that handler, check the "target" property of each event it catches and see whether its "tagName" property is "A". If so, call the handler.

The "live" feature leverages event "bubbling", which is the name for the browsers process of checking for handlers from the target element to the root of the DOM, one parent at a time. Since each <a> in your document can ultimately be traced back up to the <body>, that root node will get all the "mouseover" events that aren't shunted off by lower-level handlers that cancel bubbling (via the "stopPropagation()" method on the event object, or some weird browser-specific way I guess).

Not all events bubble, however. I'm looking around for a good reference ... ok here, the MDC page seems pretty good though a little old maybe.

like image 191
Pointy Avatar answered Nov 08 '22 04:11

Pointy