Created
July 21, 2013 01:37
-
-
Save nmoliveira/6047139 to your computer and use it in GitHub Desktop.
jQuery Custom Events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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