After learning jQuery Selectors, Attributes and Traversing methods and CSS selectors, we will now learn jQuery Events. When we design dynamic web pages, we need to apply some events such as Mouse Click, for forms submit the form after a button click, change a color after a click, etc. So in layman language, events are actions that are used for dynamic WebPages. When we perform these actions on a HTML page, we can do whatever we want.
We use some event handlers to perform the action. Some important handlebars are bind(), unbind(), blur(), off(), hover(), on(), one(), ready(), trigger() etc.
bind()
Syntax
selector.bind( eventType[, eventData], handler)
Here eventtype is a string that contains a JavaScript event type, such as submit, Click etc. Event data is in an optional thing, used to map the data to be passed to the event handler. Handler is a function to be executed each time the event is triggered. Let’s understand it using an example as in the following:
The output of the preceding code will be the as in the following:
And when we will click on any of the three DIVs, we will get an alert:
So this was the simple usage of the bind() finction.
unbind()
Syntax
selector.unbind(eventType, handler)
Here eventType is a string that contains a JavaScript event type such as submit, Click etc. Handler is a function that identifies the specific listener to be removed.
Similarly there are many other events that can be used with the bind() function.
Example
A Blur basically occurs when the element loses focus, the change is relevant when the element changes, Click is used for a mouse click, Dblclick is used for a mouse double-click etc.
Event Objects
When we want to perform an action with special handler, we used event objects, yet these are unnecessary things. Using this there are certain attributes that you would need to be accessed. Some event attributes are:
- altKey: When we press the alt key from a keyboard action it will perform (1), else false (0).
- ctrlKey: This attribute is set to true if the Ctrl key was pressed when the event was triggered, false if not.
- shiftKey: This attribute is set to true if the Shift key was pressed when the event was triggered, else false.
There are many attributes that are used here. Do more practice, you will understand more.
Here are some jQuery event methods:
Do practice with these jQuery events, you will be perfect for dynamic WebPages, comment here if you encounter any problem.
Keep Coding.