Skip to content

Instantly share code, notes, and snippets.

@nmoliveira
Created July 21, 2013 01:37
Show Gist options
  • Save nmoliveira/6047139 to your computer and use it in GitHub Desktop.
Save nmoliveira/6047139 to your computer and use it in GitHub Desktop.
jQuery Custom Events
<!DOCTYPE html>
<html>
<head>
<title>jQuery Custum Events</title>
<script src="jquery.js"></script>
<style type="text/css">
#light{
width: 100px;
height: 100px;
background-color: black;
}
.on{
background-color: yellow !important;
}
</style>
</head>
<body>
<input type="button" id="switch" value="Switch On">
<div id="light"></div>
<script type="text/javascript">
// get the light element
// toggle class
// set the right text on button
var switchTheLight = function(){
var light$ = $('#light');
light$.toggleClass('on');
light$.hasClass('on') ? $('#switch').val('Switch Off') :$('#switch').val('Switch On');
}
$(function(){
// attach custom event
var light$ = $('#light');
light$.on('switchLight', function() {
switchTheLight();
})
// on click on button trigger custom event
var switch$ = $('#switch');
switch$.on('click', function() {
$('#light').trigger('switchLight');
})
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment