I know that when using jQuery you can do $('element').click(); to catch the click event of an HTML element, but how do you do that with plain Javascript?
- 4,206
- 16
- 61
- 93
6 Answers
document.getElementById('element').onclick = function(e){
alert('click');
}
- 214,658
- 40
- 293
- 332
-
1One thing to note: the jquery selector 'element' would be for an "element" tag, i.e.
... . getElementById('element') selects the element with id "element", e.g....– Asmor Oct 26 '11 at 19:55 -
1@Asmor: True, in that case you could use `document.getElementsByTagName('div')` instead. Demo: http://jsfiddle.net/e9jZW/2/ – gen_Eric Oct 26 '11 at 20:05
By adding an event listener or setting the onclick handler of an element:
var el = document.getElementById("myelement");
el.addEventListener('click', function() {
alert("Clicked");
});
// ... or ...
el.onclick = function() {
alert("Clicked");
}
Note that the even listener style allows multiple listeners to be added whereas the callback handler style is exclusive (there can be only one).
If you need to add these handlers to multiple elements then you must acquire them as appropriate and add them to each one separately.
- 143,080
- 41
- 260
- 285
-
Is there any advantage to adding the event listener (over using onclick)? – chromedude Oct 26 '11 at 19:57
-
2In IE you have to use attachEvent rather than the standard addEventListener. – ashansky Oct 26 '11 at 19:57
-
1@chromedude: yes there are, notably that you can add multiple listeners and you can also explicitly prevent or allow event propagation to parent elements. The linked MDN page about event listeners has more information. – maerics Oct 26 '11 at 19:59
-
2@ashansky: true, IE doesn't support it until version 9, even though it is part of DOM level 2 (published in Nov 2000). – maerics Oct 26 '11 at 20:00
-
`There is a drawback to attachEvent, the value of "this" will be a reference to the window object instead of the element on which it was fired.` Goddammit IE... – gen_Eric Oct 26 '11 at 20:21
I usaly create a kind of global event handler, very powerful, you can capture className, of the event "types" nodeTypes, you name it, i hope people will find this useul
document.onclick = eventRef
function eventRef(evt) {
var han;
evt || (evt = window.event);
if (evt) {
var elem = evt.target ? han = evt.target : evt.srcElement && (han = evt.srcElement);
// evt.type could be, mouseup, mousedown...
// elem.id is the id or the element
// elem.className is the class name of the element
// you could nest expression, use substrings to extract part of a className
if (evt.type=="click" && elem.id == "gotit" || elem.className == "someClassName") {
alert(elem.id);
}
}
}
-
This seems less efficient than attaching the events to the individual element(s) you want. – gen_Eric Oct 26 '11 at 20:26
-
well it would be for one or 3 elements, ill post a example to show how its more practical to use – david Oct 26 '11 at 20:30
-
Also, this function would be called for every click even if it doesn't have an event (even on links), seems inefficient. – gen_Eric Oct 26 '11 at 20:34
-
@Rocket No rocket it wound not, and who would silly anuf to have two ID's the same :) – david Oct 26 '11 at 20:36
-
`han` seems redundant here, it's the same as `elem` and therefore isn't needed. – gen_Eric Oct 26 '11 at 20:36
-
Huh? What this have to do with having duplicate IDs? I meant that every click would call this event and then it would have to check the ID (or class or w/e). I think attaching individual events is more efficient. – gen_Eric Oct 26 '11 at 20:37
-
@Rocket if you would like to continue ide be happy go in to a chat room and ill answer your comments – david Oct 26 '11 at 20:42
-
I was just wondering if this was more or less efficient, it seems like it would be less efficient. – gen_Eric Oct 26 '11 at 20:44
-
let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4539/discussion-between-david-and-rocket) – david Oct 26 '11 at 20:47
Thanks to vanilla js
document.addEventListener('click', function (event) {
// If the clicked element doesn't have the right selector, bail
if (!event.target.matches('input')) return;
// Don't follow the link
event.preventDefault();
// Log the clicked element in the console
console.log(event.target);
}, false);
This also show which element is c
- 25
- 6
I would recommend going with addEventListener instead of assigning the handler function directly.
var div = document.getElementById('test');
div.addEventListener('click', function(){
console.log('CLICKED');
});
There are several reasons for that by I am going to name those I find the most important:
- You can't mistakenly add event listener to a non-DOM object with
addEventListener- your code would fail instead of quietly assigningonclickfunction to some object - You can attach only one (without additional code manipulation for every handler that you want to add) event listener with
onclick- something that might prove limiting
- 11,513
- 5
- 34
- 57
-
Well, you *could* attach multiple events with `onclick` if you backed up the original one first. `var _click = el.onclick; el.onclick=function(e){_click.call(this,e); //More code};`. – gen_Eric Oct 26 '11 at 20:10
-
1@Rocket 1st - thanks for the `attach` to `add` typo fix. :) Secondly, of course I could do some "aspecting" around it, problem is - someone else who is using your code, writing it in parallel or customizing it may not be so generous... – ZenMaster Oct 26 '11 at 20:14
-
Here is an interesting article about that, i used the same approach some times, basically, you add the event handler to window.
http://mislav.uniqpath.com/js/handling-events-on-elements/
- 1,907
- 19
- 22
-
Isn't attaching the event and then figuring out what to call less efficient than just attaching the event to multiple elements? – gen_Eric Oct 26 '11 at 20:43