IMG-LOGO

Event Handling in JQuery

andy - 25 Jan, 2016 3587 Views 0 Comment
Event Handling in JQuery

So what actually an event? An event can be considered as a result of an action triggered by a process which can be a process clicking of a user or when a page is loading.

In javascript, when we want to add an event to a button, we will need to use a function named addEventListener to attach an event. Please see the following example for more details.

Let says we have the following button in our page.

<p><input type="button" value="Click Me" id="btnAction"/></p>
var btn = document.getElementById("btnAction");
var eventListener = function (event) {
    alert("You have clicked me");
	event.preventDefault();
};
btn.addEventListener("click", eventListener, false);
While in JQuery, you can easily attach an event by using the following code.
$("#btnAction").click(function(event){
	alert("You have clicked me");
	event.preventDefault();
});

Alternatively in JQuery, you can use the following keyword on as well.

$("#btnAction").on("click", function(event){
	alert("You have clicked me");
	event.preventDefault();
});

So how to remove an event handler we just created from JQuery, it is pretty simple. Either you can use the keyword .off or unbind.

$("#btnAction").off("click");

// or you can use the following option
$("#btnAction").unbind("click");
The following code below is how to remove the handler using javascript.

Attaching multiple events in JQuery

Attaching multiple events in JQuery is quite simple, you can wrap the function attached separated by comma like below.

$("#btnAction").on("mouseenter", function() {
    alert("Hovering over");
}).on("mouseleave", function() {
   alert("Hovering out");
});

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Blogs

Related Tutorials

DOM Element Selection in JQuery

Learn how easily to manipulate DOM element selection using JQuery One of the cool feature from JQuery is the DOM selector In javascript when you want to reference an object you can refer the object either based on ID or ...

Writing your first JQuery function.

Getting started by writing your first JQuery code Learn how to create it from scratch and apply it on your site The best way to start your first JQuery function is after the browser has completedly loaded the page content ...

What is JQuery?

Learn what is the JQuery framework is and why many web developers and designers love to this framework.