Share on Google+Share on Google+

Bind custom event with an element using 'bind'

Advertisement
In this tutorial, we will discuss about how to bind a user define event with an element using 'bind ' function of jQuery.

Bind custom event with an element using 'bind'

In this tutorial, we will discuss about how to bind a user define event with an element using 'bind ' function of jQuery. In this example ,  we are firing an user defined event by button click. When we click on button , click event triggers user defined event "myCustomEvent", which in turn displays text message.

bindCustomEvent.html

<!DOCTYPE html>
<html>
<head>
<style>
p { color:red; }
span { color:blue; }
</style>
<script src="jquery-1.4.2.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<br><br><span style="display:none;"></span>
<script>

$("p").bind("myCustomEvent", function(e,myName, myValue){
$(this).text(myName + ", hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
});

</script>
</body>
</html>

OUTPUT

When we click on button :

Download Source Code

Click here to see demo

Advertisements

Advertisement

Posted on: August 3, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.