Introduction to JQUERY - Binding Events on any HTML Elements with bind() and on() Methods

Guest Posts Paolo Nikko Nuñal

Most of the time we associate <buttons> and links / anchor tags <a> as the elements that needs to be clicked. However, JQUERY has made it easy for us to bind event for any HTML elements. It is really cool to see divs that respond to keyup press of keyboard or see paragraphs change during a hover of a mouse pointer. All of these things are possible thanks to the bind() method.

Binding elements is easy and you can do so using this syntax.

Syntax:

$([SELECTOR]).bind([EVENT],[DATA],[FUNCTION],[MAP])

EVENT - (Required) Specifies one or more events to be attached to HTML elements. Multiple values are supported and are seperated using space.

DATA - (Optional) Specifies additional data to be passed along the function.

FUNCTION - (Required) Specifies the function to run during the event trigger.

MAP - Specifies the event map containing events that are attach to the elements and functions to run when the event happens.

In this sample code, we are going to bind an onclick event to a div.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
   $("#section").bind("click",function(){
       alert("The Div was clicked");
    });
 });
</script>
</head>
<body>
<div id="section">Div with Bind</div>
</body>
</html>


Once you click on the text, it will automatically pop-up with an alert message stating that you have clicked that specified div. You can also do other type of events like mouseover, dblclick, click, submit or mouseout just to name a few.

However, due to recent changes in JQUERY it is advisable that you use the method on().It still has the same functions with the bind() method but with a different set of parameters.

Syntax:

$([SELECTOR]).on([EVENT],[CHILDSELECTOR],[DATA],[FUNCTION],[MAP])

That's it!, know you know how to turn any HTML element to make it interactive thanks to the bind() and on() methods.