There are many ways by which we can attach an event on an HTML element.
The first way is: HTML attribute
<div id="foo" onclick="print2()> My event is attached as HTML attribute</div>
The second way is using some library (say jQuery)
<div id="bar"> My event is attached using jQuery </div>
<script>
$("#bar").click(function() {
alert("Hi this is Bar");
}
</script>
I earlier thought that jQuery might be internally converting the event to corresponding HTML attribute but this does not happen. Check this http://jsfiddle.net/blunderboy/wp4RU/3/
I am logging all the attributes of foo and bar and see bar does not have onclick attribute.
Please explain.
There is nothing called HTML Event! The two types of events you have described are, inline events and unobtrusive events, and both are javascript events.
Inline Events
When you declare javascript code on the elements itself, then it becomes an inline event. You have a few common events (as attributes to HTML Elements) like
onclick,onkeydown,onkeypress,onkeyup, and all of them start withon. One such example is:Unobtrusive Events
We need to assign something to be performed when the event is triggered. The
=symbol is always used in JavaScript to assign the value on the right to the method or property on the left.The window is not the only object we can attach events to. We can attach events to any object within the web page provided that we have a way of uniquely identifying that object. One way of identifying an object is by giving it an ID and referencing it by
document.getElementById("id_of_the_element").Lets take the same example.
Instead of the
onclickattribute, I have anIDin the same place, which uniquely identifies the HTML element<a>. Now I can get the ID inside javascript this way:For this, I can attach an event handler, which doesn’t differ much from the way we use the attributes. It just doesn’t have the
onin the front. In our previous example, we usedonclick, but now we are just going to useclick.Here, the
functionNamerefers to any javascript’s function name, or an anonymous function. So, for the alert, if we create a function namedalertme(), we can define this way:Now to attach the function to the element can be done this way:
Still feeling lazy, you can do it using the anonymous function way, which takes no name:
Hope you understood. 🙂 Let me know for further clarification.