As we’ve previously seen in our Introduction to Events, adding event listeners is fairly easy. The question then becomes, when would you need to use them? And to what can we attach them?
Well, we can attach them to any visible element. So, for example, tags are not going to be useful, however divs, spans, etc can all have event handlers. Some, like text boxes, allow other event handlers.
You will notice that I often use ID selectors when I attach an event handler. This is because I want to make sure I am not applying a method to multiple elements on my web page. I usually want buttons and event handlers to be unique.
What is “this”
this is a special keyword in JavaScript. It means you are talking about the current object, or item if you prefer a simpler notation. So you will see it often in jQuery event handlers, because it references the item that has had the event fire. For example, lets say you want to toggle a class when an item is clicked.
$('#buttona').click(function() { this.toggleClass('pressed'); });
So what is an Object?
For this class, you don’t have to know too much about classes, objects, etc. But as you may see this information around in other places, I want to give you a quick overview.
An object is an instantiation of complex data type, often having several internal variables and functions, built from a class.
OK think of it this way: You have a person. This person cannot be viewed as a simple data structure like a string – there are too many elements about them. There is name, phone number, address, DOB, employee/student/social security number.
An class lets you define what the data will be, and reference, much like a recipe. The object is built from that class (recipe) and has values in each of those data elements.
Referencing Other Elements
Of course you can refer to other elements as well. You just need to reference their selector via jQuery. So lets say you want to hide another element when a button is pressed.
$('#hideit').click(function() { $('#tobehidden').hide(); });
.hide() is a built in function that jQuery gives us to make an element invisible. There is also a .show(), and a .toggle() that we have access to. These allow us to change what is or isn’t visible on the screen. We can also create a class that will perform a similar function, by addClass(), removeClass(), and toggleClass() – but that is not the standard way of doing it in jQuery.
Additionally, in the up coming sessions, you will see how we can adjust the value of objects, change out the content of an object, and much, much more.
Using Events in jQuery was originally found on Access 2 Learn