user979672
user979672

Reputation: 1843

JavaScript: capturing events regardless of element

  1. Is there any existing mechanism by which I can add an event listener to 'focus' for all the DOM elements on the page that have this event? If not, how might I do that?

  2. I'd like to console.log(something) any time any DOM element fires an event. How might I do this?

EDIT: Without any framework please :)

Upvotes: 0

Views: 132

Answers (4)

Juri
Juri

Reputation: 32950

Something like this should work (with jQuery).

$("input").focus(function(){
   console.log($(this).attr("id"));
});

Here's a live example: http://jsbin.com/ipiciz/edit#javascript,html,live

Upvotes: 0

arb
arb

Reputation: 7863

You could try using the :input pseudo selector in jQuery.

$(':input').focus(function(e){
    console.log(e);
});

This will only attach to the input elements which is probably what you're looking for anyway.

Upvotes: 0

nafisto
nafisto

Reputation: 449

Events "bubble" up through the DOM, so you should be able to bind a listener to document, body, html, or any other parent element (e.g. a div) and listen for every event triggered by elements that it contains.

For example, using JQuery, you could do it like this:

$(document).bind('focus', function(e) { console.log(e); });

This will log every focus event, no matter what element initially triggers the event.

Upvotes: 0

Keith.Abramo
Keith.Abramo

Reputation: 6965

You can bind the event to the body or html element. Or any other element which encloses all of your html.

Or if you want to use jQuery you could do something like

$("*").bind("focus", function(e){
    console.log("something");
})

Upvotes: 1

Related Questions