Skip to content

Instantly share code, notes, and snippets.

@hcmn
Created July 11, 2012 18:44
Show Gist options
  • Save hcmn/3092296 to your computer and use it in GitHub Desktop.
Save hcmn/3092296 to your computer and use it in GitHub Desktop.
JQuery: a custom event with click() & trigger()
<!DOCTYPE html>
<html>
<head>
<style>
p { color:red; }
span { color:blue; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
</body>
</html>
$(function() {
$("p").on("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
// $(this).text(myName.name + ", hi there!"); accessing event object
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
// $("p").trigger("myCustomEvent", { name: "John"}); passing an event object
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment